Spring Boot+Spring Security系列博客中使用的共用类

  • MyUser: 实体类
public class MyUser implements Serializable {
    private static final long serialVersionUID = 3497935890426858541L;

    private String userName;

    private String password;

    private boolean accountNonExpired = true;

    private boolean accountNonLocked= true;

    private boolean credentialsNonExpired= true;

    private boolean enabled= true;

    // get,set略,推荐使用快捷键生成
  • UserDetailService: 实现UserDetailsService接口
@Configuration
public class UserDetailService implements UserDetailsService {

    @Autowired
    private PasswordEncoder passwordEncoder;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        // 模拟一个用户,替代数据库获取逻辑
        MyUser user = new MyUser();
        user.setUserName(username);
        user.setPassword(this.passwordEncoder.encode("123456"));
        // 输出加密后的密码
        System.out.println(user.getPassword());

        return new User(username, user.getPassword(), user.isEnabled(),
                user.isAccountNonExpired(), user.isCredentialsNonExpired(),
                user.isAccountNonLocked(), AuthorityUtils.commaSeparatedStringToAuthorityList("admin"));
    }
}
  • IndexController:跳转到index页面控制器
@RestController
public class IndexController {
    @GetMapping("index")
    public Object index(){
        return SecurityContextHolder.getContext().getAuthentication();
    }
}
  • MySecurityController:是否能访问静态资源的控制器
@RestController
public class MySecurityController {
	//RequestCache requestCache是Spring Security提供的用于缓存请求的对象
    private RequestCache requestCache = new HttpSessionRequestCache();
	//DefaultRedirectStrategy是Spring Security提供的重定向策略
    private RedirectStrategy redirectStrategy = new DefaultRedirectStrategy();

    @GetMapping("/authentication/require")
    @ResponseStatus(HttpStatus.UNAUTHORIZED)
    public String requireAuthentication(HttpServletRequest request, HttpServletResponse response) throws IOException {
				//getRequest方法能够获取到本次请求的HTTP信息
        SavedRequest savedRequest = requestCache.getRequest(request, response);
        if (savedRequest != null) {
            String targetUrl = savedRequest.getRedirectUrl();
            if (StringUtils.endsWithIgnoreCase(targetUrl, ".html"))
							//sendRedirect为Spring Security提供的用于处理重定向的方法
                redirectStrategy.sendRedirect(request, response, "/login.html");
        }
        return "访问的资源须要身份认证!";
    }
}
  • MySecurityConfig:SpringSecurity的配置类
@Component
public class MySecurityConfig extends WebSecurityConfigurerAdapter {
    @Autowired
    private MyAuthenticationFailureHandler authenticationFailureHandler;

    @Autowired
    private MyAuthenticationSuccessHandler authenticationSuccessHandler;
    @Autowired
 private ValidateCodeFilter validateCodeFilter;
    @Bean
    public BCryptPasswordEncoder bCryptPasswordEncoder(){
        return new BCryptPasswordEncoder();
    }
    @Override
    protected void configure(HttpSecurity http) throws Exception {
         http.formLogin() // 表单登陆
                // http.httpBasic() // HTTP Basic
                .loginPage("/authentication/require") // 登陆跳转 URL
                .loginProcessingUrl("/login") // 处理表单登陆 URL
                .failureHandler(authenticationFailureHandler) // 处理登陆失败
                .successHandler(authenticationSuccessHandler)
                .and()
                .authorizeRequests() // 受权配置
                .antMatchers("/authentication/require",
                        "/login.html").permitAll() // 无需认证的请求路径
                .anyRequest()  // 全部请求
                .authenticated() // 都须要认证
                .and().csrf().disable();
    }
}
  • MyAuthenticationFailureHandler:请求失败的配置类(在SpringSecurity的配置类中使用)
@Component
public class MyAuthenticationFailureHandler implements AuthenticationFailureHandler {

    @Autowired
    private ObjectMapper mapper;

    @Override
    public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response,
                                        AuthenticationException exception) throws IOException {
        response.setStatus(HttpStatus.INTERNAL_SERVER_ERROR.value());
        response.setContentType("application/json;charset=utf-8");
        response.getWriter().write(mapper.writeValueAsString(exception.getMessage()));
    }
}
  • MyAuthenticationSuccessHandler:请求成功的配置类(在SpringSecurity的配置类中使用)
@Component
public class MyAuthenticationSuccessHandler implements AuthenticationSuccessHandler {

       private RedirectStrategy redirectStrategy = new DefaultRedirectStrategy();

       @Override
       public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response,
                                           Authentication authentication) throws IOException {
           redirectStrategy.sendRedirect(request, response, "/index");
       }

}
相关文章
相关标签/搜索