基於註解方式的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;
}
}