SpringSecurity在SpringBoot 的实际应用

来源:互联网 发布:库存查询软件 编辑:程序博客网 时间:2024/06/08 02:16
  • SpringSecurity是Spring的一个安全框架,它的前身是Acegi Security.这个框架主要分为两个部分,认证、验证。
  • 本教程是基于SpringBoot的环境
  • 导入依赖
  <!-- spring安全 -->        <dependency>            <groupId>org.springframework.boot</groupId>            <artifactId>spring-boot-starter-security</artifactId>        </dependency>
  • 新建WebSecurityAdapter类并继承WebSecurityConfigurerAdapter,WebSecurityConfigurerAdapter是security提供用于更改默认配置,实现configure方法,代码如下:
@Configuration@EnableWebSecuritypublic class WebSecurityAdapter extends WebSecurityConfigurerAdapter {    /**定义安全策略*/    @Override    protected void configure(HttpSecurity http) throws Exception {        http.csrf().disable();        http.authorizeRequests()                .antMatchers("/",,"/login/**","/login/auth").permitAll()//定义/请求不需要验证                .antMatchers("/admin/**").authenticated()//其余的所有请求都需要验证                .and().rememberMe().tokenValiditySeconds(3600)                .and().formLogin().loginPage("/login").defaultSuccessUrl("/admin/article/list").permitAll()//使用form表单登录                .and().logout().logoutUrl("/admin/loginOut").permitAll();//定义logout不需要验证    }    @Override    public void configure(WebSecurity web) throws Exception {        web.ignoring().antMatchers("/**/*.*");    }    /**定义认证用户信息获取来源,密码校验规则等*/    @Override    protected void configure(AuthenticationManagerBuilder auth) throws Exception {        auth.authenticationProvider(authenticationProvider());    }    @Bean    public AuthenticationProvider authenticationProvider(){        AuthenticationProvider authenticationProvider=new CustomAuthenticationProvider();        return authenticationProvider;    }}
  • 自定义CustomAuthenticationProvider 继承 AuthenticationProvider来实现安全策略和认证
@Configuration@EnableWebSecuritypublic class CustomAuthenticationProvider implements AuthenticationProvider {    @Autowired    private UserService userService;    @Override    public Authentication authenticate(Authentication authentication) throws AuthenticationException {        UsernamePasswordAuthenticationToken token = (UsernamePasswordAuthenticationToken) authentication;        String username = token.getName();        //从数据库找到的用户        User user = null;        if (username != null) {            user = userService.loadUserByUsername(username);        }        //        if (user == null) {            throw new UsernameNotFoundException("用户名/密码无效");        } else if (user.isEnabled()) {            throw new DisabledException("用户已被禁用");        } else if (user.isAccountNonExpired()) {            throw new AccountExpiredException("账号已过期");        } else if (user.isAccountNonLocked()) {            throw new LockedException("账号已被锁定");        } else if (user.isCredentialsNonExpired()) {            throw new LockedException("凭证已过期");        }        //数据库用户的密码        String password = user.getPassword();        String pwdDigest = Md5Util.pwdDigest(token.getCredentials().toString());        //与authentication里面的credentials相比较        if (!password.equals(pwdDigest)) {            throw new BadCredentialsException("Invalid username/password");        }        HttpServletRequest request = ((ServletRequestAttributes)RequestContextHolder.getRequestAttributes()).getRequest();        HttpSession session = request.getSession();        session.setAttribute("user",user);        //授权        return new UsernamePasswordAuthenticationToken(user, password, user.getAuthorities());    }    public void config(WebSecurity web) {        web.ignoring().antMatchers("/js/**", "/css/**", "/vendor/**", "/image/**", "/admin/**");    }    @Override    public boolean supports(Class<?> authentication) {        return UsernamePasswordAuthenticationToken.class.equals(authentication);    }}
  • 本文通过完成了对Web应用的安全控制,Spring Security提供的功能还远不止于此,更多Spring Security的使用可参见Spring Security Reference。
原创粉丝点击