Navigation Menu

Skip to content

Instantly share code, notes, and snippets.

@phuonghuynh
Last active March 7, 2023 11:17
Show Gist options
  • Star 13 You must be signed in to star a gist
  • Fork 3 You must be signed in to fork a gist
  • Save phuonghuynh/6bbd04291958895ec2da to your computer and use it in GitHub Desktop.
Save phuonghuynh/6bbd04291958895ec2da to your computer and use it in GitHub Desktop.
Spring Security - Multiple Authentication Providers
public class AuthenticationToken extends AbstractAuthenticationToken {
private String token;
public AuthenticationToken(String token) {
super(null);
this.token = token;
setAuthenticated(false);
}
public AuthenticationToken(String token, Collection<? extends GrantedAuthority> authorities) {
super(authorities);
this.token = token;
super.setAuthenticated(true);
}
public Object getCredentials() {
return null;
}
public String getToken() {
return token;
}
public Object getPrincipal() {
return token;
}
public void setAuthenticated(boolean isAuthenticated) throws IllegalArgumentException {
if (isAuthenticated) {
throw new IllegalArgumentException(
"Cannot set this token to trusted - use constructor which takes a GrantedAuthority list instead");
}
super.setAuthenticated(false);
}
public void eraseCredentials() {
super.eraseCredentials();
token = null;
}
}
public class AuthenticationTokenFilter extends AbstractAuthenticationProcessingFilter {
private String authHeaderName = "bizi-auth-token";
public final static String LOGIN_URL = "/login/authToken";
public AuthenticationTokenFilter() {
super(new AntPathRequestMatcher(LOGIN_URL));
}
public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response) throws AuthenticationException, IOException, ServletException {
String token = request.getHeader(authHeaderName);
AuthenticationToken authRequest = new AuthenticationToken(token);
authRequest.setDetails(authenticationDetailsSource.buildDetails(request));
return this.getAuthenticationManager().authenticate(authRequest);
}
}
public class AuthenticationTokenProvider implements AuthenticationProvider {
@Transactional(Transactional.TxType.REQUIRES_NEW)
public Authentication authenticate(Authentication authentication) throws AuthenticationException {
Assert.isTrue(!authentication.isAuthenticated(), "Already authenticated");
AuthenticationToken authenticationToken = (AuthenticationToken) authentication;
if (!StringUtils.hasText((String) authenticationToken.getToken())) {
throw new InternalAuthenticationServiceException("Token must not be empty");
}
/**TODO do the logic here and return not null authentication object*/
return null;
}
public boolean supports(Class<?> authentication) {
return (AuthenticationToken.class.isAssignableFrom(authentication));
}
}
public class InternalAuthenticationProvider implements AuthenticationProvider {
@Transactional(Transactional.TxType.REQUIRES_NEW)
public Authentication authenticate(Authentication authentication) throws AuthenticationException {
Assert.isTrue(!authentication.isAuthenticated(), "Already authenticated");
if (!StringUtils.hasText(authentication.getPrincipal().toString())) {
throw new InternalAuthenticationServiceException("User key must not be empty.");
}
/**TODO do the logic here and return not null authentication object*/
return null;
}
public boolean supports(Class<?> authentication) {
return (UsernamePasswordAuthenticationToken.class.isAssignableFrom(authentication));
}
}
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true)
@EnableRedisHttpSession
public class SecurityConfiguration extends WebSecurityConfigurerAdapter {
/**removed code*/
@Bean
public AuthenticationProvider internalAuthenticationProvider() {
return new InternalAuthenticationProvider();
}
@Bean
public AuthenticationProvider authenticationTokenProvider() {
return new AuthenticationTokenProvider();
}
@Bean
public AuthenticationManager authenticationManager() {
return new ProviderManager(Arrays.asList(internalAuthenticationProvider(), authenticationTokenProvider()));
}
@Bean
public AuthenticationTokenFilter authenticationTokenFilter() {
AuthenticationTokenFilter filter = new AuthenticationTokenFilter();
filter.setAuthenticationManager(authenticationManager());
filter.setAuthenticationSuccessHandler(getSuccessHandler());
filter.setAuthenticationFailureHandler(getAuthenticationFailureHandler());
filter.setAllowSessionCreation(true);
return filter;
}
protected void configure(HttpSecurity http) throws Exception {
http.csrf().disable();
http.authorizeRequests()
.and().formLogin()
.loginPage("/login").usernameParameter("us").passwordParameter("pwd")
.successHandler(getSuccessHandler()).failureHandler(getAuthenticationFailureHandler())
.and().logout()
.logoutUrl("/logout").logoutSuccessHandler(getLogoutSuccessHandler()).invalidateHttpSession(true)
.deleteCookies("SESSION").permitAll()
.and().exceptionHandling().authenticationEntryPoint(exceptionHandler())
.and().addFilterBefore(authenticationTokenFilter(), FilterSecurityInterceptor.class);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment