springboot整合springsecurity

1.引入springsecurity的启动依赖

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

2.增加配置类

@Configuration
@EnableWebSecurity
public class DemoSecurity extends WebSecurityConfigurerAdapter {
    @Autowired
    private UserService userService;

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        //配置用户数据从数据库中读取,密码使用NoOpPasswordEncoder类加密处理(明文密码),
        //如果数据库里的密码字段使用了md5等加密,这里就要用相应的加密类处理
        auth.userDetailsService(userService).passwordEncoder(NoOpPasswordEncoder.getInstance());
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.authorizeRequests()
                .antMatchers("/css/**").permitAll()//配置不进行权限校验的url
                .antMatchers("/tologin").permitAll()
                .antMatchers("/mylogin").permitAll()
                .antMatchers("/**").authenticated()//配置拦截校验所有请求(这里会自动放开前面配置的不进行校验的url)
                .and().formLogin()//登录相关配置
                    .loginPage("/tologin")//登录页面
                    .loginProcessingUrl("/mylogin")//登录表单提交的url,这里配置什么值,表单的action中就填写这个url
                    .usernameParameter("myusername")//登录表单提交的用户名参数名称
                    .passwordParameter("mypassword")//登录表单提交的密码参数名称
                    .successHandler(authenticationSuccessHandler())//登录成功后,跳转的主页
                    .failureHandler(authenticationFailureHandler())//登录失败处理
                .and().logout()//登出相关配置
                    .logoutRequestMatcher(new AntPathRequestMatcher("/mylogout", "GET")).logoutSuccessUrl("/tologin")
                .and().exceptionHandling()//校验异常相关配置
                    .accessDeniedPage("/mycontroller/401");//登录成功后访问没有权限的资源
    }

    public AuthenticationFailureHandler authenticationFailureHandler() {
        return new AuthenticationFailureHandler() {
            @Override
            public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response, AuthenticationException exception) throws IOException, ServletException {
                request.setAttribute("msg","用户名或密码错误!");//返回错误信息
                request.getRequestDispatcher("/tologin").forward(request,response);//转发的到登录界面
            }
        };
    }

    public AuthenticationSuccessHandler authenticationSuccessHandler() {
      return   new AuthenticationSuccessHandler() {
            @Override
            public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException, ServletException {
                request.getRequestDispatcher("/mycontroller/test?msg=1234").forward(request,response);//登录成功后转发至首页
            }
        };
    }
}

3.从数据库获取权限信息,userservice要实现org.springframework.security.core.userdetails.UserDetailsService接口

@Service
public class UserService implements UserDetailsService {
    @Autowired
    private UserDao userDao;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        User user = userDao.selectUserAndRoles(username);
        if (user == null) {
            return new User();
        }
        return  user;
    }
}

4.User实体要实现org.springframework.security.core.userdetails.UserDetails接口

public class User implements Serializable, UserDetails {
    private Integer id;

    private Integer age;

    private String password;

    private String username;

    private Integer ctryId;
    private List<Role> roles;

   //用户权限数据
    @Override
    public Collection<? extends GrantedAuthority> getAuthorities() {
        return roles;
    }

    //账号没有过期
    @Override
    public boolean isAccountNonExpired() {
        return true;
    }

    //账号没有锁定
    @Override
    public boolean isAccountNonLocked() { return true; }

    //证书没有过期
    @Override
    public boolean isCredentialsNonExpired() { return true; }

    //客户有效
    @Override
    public boolean isEnabled() {
        return true;
    }
}

5.Role实体要实现org.springframework.security.core.GrantedAuthority接口

public class Role implements GrantedAuthority {
    private int id;
    private String roleName;
    
    //角色名称
    @Override
    public String getAuthority() {
        return this.roleName;
    }
}

6.thmeleaf中使用springsecurity的标签

   引入依赖

 <dependency>
       <groupId>org.thymeleaf.extras</groupId>
       <artifactId>thymeleaf-extras-springsecurity4</artifactId>
       <version>3.0.2.RELEASE</version>
 </dependency>

 页面添加命名空间

<html lang="en" xmlns:th="http://www.thymeleaf.org"
                xmlns:sec="http://www.thymeleaf.org/thymeleaf-extras-springsecurity4">

 

注意:在使用hasRole判断权限时,例如hasRole('admin') ,数据库中的角色名称必须是ROLE_admin。因为springsecurity在实现hasRole方法时,会自动在admin前增加ROLE_前缀

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值