美文网首页
Spring Boot安全

Spring Boot安全

作者: 虫儿飞ZLEI | 来源:发表于2019-03-04 22:14 被阅读0次

主要有shiro和Spring Security
本文主要关注Spring Security,shiro以后再说

1.简单使用

1.1 导包

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-security</artifactId>
        </dependency>

1.2 编写SpringSecurity的配置类

@EnableWebSecurity
public class MySecurityConfig extends WebSecurityConfigurerAdapter {

1.3 定制请求的授权规则&定义认证规则

@EnableWebSecurity
public class MySecurityConfig extends WebSecurityConfigurerAdapter {

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        //定制请求的授权规则
        //访问/level1路径下的文件,需要vip1,
        //访问/level2路径下的文件,需要vip2,
        //访问/level3路径下的文件,需要vip3,
        http.authorizeRequests().antMatchers("/").permitAll()
                .antMatchers("/level1/**").hasRole("VIP1")
                .antMatchers("/level2/**").hasRole("VIP2")
                .antMatchers("/level3/**").hasRole("VIP3");
                
                //如果没有对应的role,则跳转到/login下的登录页面,自带了一个简单的登录页面
                //如果跳转/login失败,则重定向到/login?error,表示登录失败
                http.formLogin();

                //开启自动配置的注销功能。
                //自带了一个注销的页面,访问/logout,就可以看到自带的注销页面
                //注销成功以后就会自动访问/login?logout
                 http.logout();


                //开启记住我功能
                //开启后,在自带的登录页面下面会有一个勾选框,勾选后,会自动保存数据到cookie,
                //在注销页面注销以后会删除cookie
                http.rememberMe()
    }

    //定义认证规则
    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        //这些数据是保存在内存中的
        auth.inMemoryAuthentication()
                .withUser("zhangsan").password("123456").roles("VIP1","VIP2")
                .and()
                .withUser("lisi").password("123456").roles("VIP2","VIP3")
                .and()
                .withUser("wangwu").password("123456").roles("VIP1","VIP3");

                //添加完成后就可以使用这些用户密码登录了,而且这些用户携带了不同的role
    }
}

1.4 在html里面可以获取到关于权限的一些东西

导包(还需要thymeleaf的包,这里不写)

        <!-- https://mvnrepository.com/artifact/org.thymeleaf.extras/thymeleaf-extras-springsecurity4 -->
        <dependency>
            <groupId>org.thymeleaf.extras</groupId>
            <artifactId>thymeleaf-extras-springsecurity4</artifactId>
        </dependency>

引入命名空间

xmlns:sec="http://www.thymeleaf.org/thymeleaf-extras-springsecurity4"

使用

<div sec:authorize="isAuthenticated()">
    这里的div,需要登录以后才可以显示,没登陆就不显示
</div>

//显示登录的用户名
<span sec:authentication="name"></span>
//显示对应的用户名拥有的role
<span sec:authentication="principal.authorities"></span>


<div sec:authorize="hasRole('VIP1')">
      //这里必须登录,并且登录的用户拥有VIP1的role
</div>

未完待续

相关文章

网友评论

      本文标题:Spring Boot安全

      本文链接:https://www.haomeiwen.com/subject/wkswuqtx.html