Authentication success handler

We set up a custom AuthenticationSuccessHandler (the source code for this class is shown next) in our Spring Security configuration class. On successful authentication, it will generate the JWT and also set a HTTP response header:

  • Header name: Authorization
  • Header value: Bearer JWT

Let's take a look at the following code:

public class JWTAuthSuccessHandler implements ServerAuthenticationSuccessHandler{
@Override
public Mono<Void> onAuthenticationSuccess(WebFilterExchange
webFilterExchange, Authentication authentication) {
ServerWebExchange exchange = webFilterExchange.getExchange();
exchange.getResponse()
.getHeaders()
.add(HttpHeaders.AUTHORIZATION,
getHttpAuthHeaderValue(authentication));
return webFilterExchange.getChain().filter(exchange);
}
private static String getHttpAuthHeaderValue(Authentication authentication){
return String.join(" ","Bearer",tokenFromAuthentication(authentication));
}
private static String tokenFromAuthentication(Authentication authentication){
return new JWTUtil().generateToken(
authentication.getName(),
authentication.getAuthorities());
}
}

The JWTUtil class contains a number of utility methods dealing with the JWTs, such as the generation of tokens, verification of tokens, and so on. The generateToken method in the JWTUtil class is as shown here:

public static String generateToken(String subjectName, Collection<? extends             GrantedAuthority> authorities) {
JWTClaimsSet claimsSet = new JWTClaimsSet.Builder()
.subject(subjectName)
.issuer("javacodebook.com")
.expirationTime(new Date(new Date().getTime() + 30 * 1000))
.claim("auths", authorities.parallelStream().map(auth -> (GrantedAuthority) auth).map(a ->
a.getAuthority()).collect(Collectors.joining(",")))
.build();
SignedJWT signedJWT = new SignedJWT(new JWSHeader(JWSAlgorithm.HS256), claimsSet);
try {
signedJWT.sign(JWTUtil.getJWTSigner());
} catch (JOSEException e) {
e.printStackTrace();
}
return signedJWT.serialize();
}
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.145.164.80