目录
maven 依赖
selfUserDetails
SelfUserDetailsService
DefaultPasswordEncoder
JwtTokenUtil
MyAccessDenieDHandler
TokenAuthenticationFilter
TokenLoginFilter
maven 依赖
org.springframework.boot
spring-boot-starter-security
org.springframework.security
spring-security-test
io.jsonwebtoken
jjwt
0.9.0
文件目录
SpringSecurityConfig
public class SpringSecurityConfig extends WebSecurityConfigurerAdapter {
@Autowired
DefaultPasswordEncoder defaultPasswordEncoder;
@Autowired
SelfUserDetailsService selfUserDetailsService;
@Autowired
AppFilterInvocationSecuritymetadataSource appFilterInvocationSecuritymetadataSource;
@Autowired
CustomerAccessDecisionManger customerAccessDecisionManger;
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
// 加入自定义的安全认证
// auth.authenticationProvider(provider);
auth.userDetailsService(selfUserDetailsService).passwordEncoder(new BCryptPasswordEncoder());
}
@Override
protected void configure(HttpSecurity http) throws Exception {
http
.exceptionHandling()
//未授权处理
.authenticationEntryPoint(new UnauthorizedEntryPoint())
.accessDeniedHandler(new MyAccessDeniedHandler())
.and().authorizeRequests().withObjectPostProcessor(new ObjectPostProcessor() {
@Override
public O postProcess(O o) {
o.setSecuritymetadataSource(appFilterInvocationSecuritymetadataSource);
o.setAccessDecisionManager(customerAccessDecisionManger);
return o;
}
})
.anyRequest().authenticated()
.and().csrf().disable()
.logout().logoutUrl("/logout")
.and()
//.addLogoutHandler(new TokenLogoutHandler(tokenManager))
.addFilter(new TokenAuthenticationFilter(authenticationManager()))
.addFilter(new TokenLoginFilter(authenticationManager())).httpBasic();
}
@Bean
protected AuthenticationManager authenticationManager() throws Exception {
return super.authenticationManager();
}
@Bean
public DefaultPasswordEncoder CreateEncoder(){
return new DefaultPasswordEncoder();
}
@Override
public void configure(WebSecurity web) throws Exception {
web.ignoring().antMatchers("/Account
@Override
protected void successfulAuthentication(HttpServletRequest request, HttpServletResponse response, FilterChain chain, Authentication auth) throws IOException, ServletException {
SelfUserDetails user= (SelfUserDetails) auth.getPrincipal();
Account account = user.getAccount();
String authrorities = user.getAuthorities().size() > 0 ? user.getAuthorities().toString().replaceAll("(?:\[|null|\]| +)", "") : user.getAuthorities().toString();
String token=JwtTokenUtil.createToken(account.getName(),authrorities);
HashMap



