基于注解方式的Security 自定义 token登陆
首先是 Security的配置
必须基础AbstractSecurityWebApplicationInitializer
public class SecurityWebInitializer extends AbstractSecurityWebApplicationInitializer {
}
然后是配置
@Configurable
@EnableWebMvcSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Override
public void configure(WebSecurity web) throws Exception {
super.configure(web);
}
@Override
protected void configure(HttpSecurity http) throws Exception {
// super.configure(http);
//添加自定义拦截器
http.addFilterBefore(filter(), UsernamePasswordAuthenticationFilter.class);
//设置过滤规则
http.csrf().disable().formLogin().defaultSuccessUrl("/home").and().logout().and().authorizeRequests()
.antMatchers("/home").hasAnyRole("ADMIN", "USER").anyRequest().permitAll().and().rememberMe()
.key("spittr");
// 单点登录
http.sessionManagement().maximumSessions(1).maxSessionsPreventsLogin(false).expiredUrl("/login");
}
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
// super.configure(auth);
//内存用户认证
// auth.inMemoryAuthentication().withUser("user").password("password").roles("USER").and().withUser("admin")
// .password("password").roles("USER", "ADMIN").and().withUser("222")
// .password("s").roles("USER", "ADMIN");
//默认登陆的认证器
// auth.userDetailsService(new SpitterUserService());
//添加自定义拦截器
auth.authenticationProvider(authenticationProvider());
// AuthenticationProvider authenticationProvider; SimpleUrlAuthenticationSuccessHandler
}
@Bean
@Override
public AuthenticationManager authenticationManagerBean() {
try {
return super.authenticationManagerBean();
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
@Bean
public Filter filter() {
TokenAuthenticationProcessingFilter filter = new TokenAuthenticationProcessingFilter();
filter.setAuthenticationManager(authenticationManagerBean());
// filter.setSessionAuthenticationStrategy(sessionStrategy());
// AuthenticationSuccessHandler successHandler = new SimpleUrlAuthenticationSuccessHandler();
// filter.setAuthenticationSuccessHandler(successHandler );
return filter;
}
@Bean
public SessionAuthenticationStrategy sessionStrategy(){
return new ConcurrentSessionControlStrategy(new SessionRegistryImpl());
}
@Bean
public AuthenticationProvider authenticationProvider() {
TokenAuthenticationProvider tokenServer = new TokenAuthenticationProvider();
return tokenServer;
}
}
注意 @EnableWebMvcSecurity 开始Security
拦截器
public class TokenAuthenticationProcessingFilter extends AbstractAuthenticationProcessingFilter {
public TokenAuthenticationProcessingFilter() {
super("/home");
}
@Override
public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response)
throws AuthenticationException, IOException, ServletException {
String token = request.getParameter("token");
TokenAuthenticationToken upToken= new TokenAuthenticationToken();
upToken.setToken(token);
upToken.setCredentials("s");
System.out.println(this.getAuthenticationManager());
upToken.setDetails(this.authenticationDetailsSource.buildDetails(request));
return this.getAuthenticationManager().authenticate(upToken);
}
@Override
public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain)
throws IOException, ServletException {
String token = req.getParameter("token");
if(StringUtils.isEmpty(token)){
chain.doFilter(req, res);
return;
}
super.doFilter(req, res, chain);
}
}
认证器
public class TokenAuthenticationProvider implements AuthenticationProvider {
@Override
public Authentication authenticate(Authentication authentication) throws AuthenticationException {
System.out.println(authentication.getCredentials());
System.out.println("user name: " + authentication.getName());
// password
System.out.println("password: " + authentication.getCredentials());
System.out.println("getPrincipal: " + authentication.getPrincipal());
System.out.println("getAuthorities: " + authentication.getAuthorities());
System.out.println("getDetails: " + authentication.getDetails());
TokenAuthenticationToken token = (TokenAuthenticationToken) authentication;
Spitter s = new Spitter();
s.setName(token.getName());
s.setPwd((String) token.getCredentials());
// 认证成功
s.setAuthenticated(true);
Set<GrantedAuthority> authoritys = new HashSet<GrantedAuthority>();
authoritys.add(new SimpleGrantedAuthority("ROLE_USER"));
s.setAccesses(authoritys);
s.setDetails(authentication.getDetails());
return s;
}
@Override
public boolean supports(Class<?> authentication) {
return authentication.equals(TokenAuthenticationToken.class);
}
}
public class TokenAuthenticationToken extends AbstractAuthenticationToken {
private String token;
private String credentials;
public String getToken() {
return token;
}
public void setToken(String token) {
this.token = token;
}
public TokenAuthenticationToken() {
super(null);
}
public TokenAuthenticationToken(Collection<? extends GrantedAuthority> authorities) {
super(authorities);
}
@Override
public Object getCredentials() {
return this.credentials;
}
@Override
public Object getPrincipal() {
return token;
}
public void setCredentials(String credentials) {
this.credentials = credentials;
}
}
public class Spitter implements Authentication {
/**
*
*/
private static final long serialVersionUID = 1L;
private String name;
private String pwd;
private String loginName;
private Object details;
@Override
public String getName() {
return name;
}
//权限
private Set<GrantedAuthority> accesses;
/**
* 获取权限
*/
@Override
public Collection<GrantedAuthority> getAuthorities() {
return accesses;
}
@Override
public Object getCredentials() {
return pwd;
}
@Override
public Object getDetails() {
return details;
}
@Override
public Object getPrincipal() {
return name;
}
//判断是否验证
private boolean authenticated=false;
/**
* 是否已验证
*/
@Override
public boolean isAuthenticated() {
return this.authenticated;
}
@Override
public void setAuthenticated(boolean arg0) throws IllegalArgumentException {
this.authenticated=arg0;
}
public String getLoginName() {
return loginName;
}
public void setLoginName(String loginName) {
this.loginName = loginName;
}
public Set<GrantedAuthority> getAccesses() {
return accesses;
}
public void setAccesses(Set<GrantedAuthority> accesses) {
this.accesses = accesses;
}
public String getPwd() {
return pwd;
}
public void setPwd(String pwd) {
this.pwd = pwd;
}
public void setName(String name) {
this.name = name;
}
public void setDetails(Object details) {
this.details = details;
}
}