Search in sources :

Example 81 with JWT

use of com.auth0.jwt.JWT in project snow-owl by b2ihealthcare.

the class JWTConfigurationTest method hs256.

@Test
public void hs256() throws Exception {
    IdentityConfiguration conf = readConfig("hs256.yml");
    new IdentityPlugin().configureJWT(services, identityProvider, conf);
    // generate a key then verify it without errors
    String jwt = services.getService(JWTGenerator.class).generate("test@example.com", Map.of());
    DecodedJWT decoded = services.getService(JWTVerifier.class).verify(jwt);
    assertThat(decoded.getAlgorithm()).isEqualTo("HS256");
}
Also used : DecodedJWT(com.auth0.jwt.interfaces.DecodedJWT) JWTVerifier(com.auth0.jwt.interfaces.JWTVerifier) Test(org.junit.Test)

Example 82 with JWT

use of com.auth0.jwt.JWT in project flow by vaadin.

the class JwtSecurityUtils method getAuthenticatedUser.

public UserDetails getAuthenticatedUser() {
    SecurityContext context = SecurityContextHolder.getContext();
    Object principal = context.getAuthentication().getPrincipal();
    if (principal instanceof Jwt) {
        String userName = ((Jwt) principal).getClaim("sub");
        return new User(userName, "", Collections.emptyList());
    }
    // Anonymous or no authentication.
    return null;
}
Also used : User(org.springframework.security.core.userdetails.User) Jwt(org.springframework.security.oauth2.jwt.Jwt) SecurityContext(org.springframework.security.core.context.SecurityContext)

Example 83 with JWT

use of com.auth0.jwt.JWT in project spring-security by spring-projects.

the class OAuth2LoginBeanDefinitionParserTests method requestWhenCustomGrantedAuthoritiesMapperThenCalled.

@SuppressWarnings({ "unchecked", "rawtypes" })
@Test
public void requestWhenCustomGrantedAuthoritiesMapperThenCalled() throws Exception {
    this.spring.configLocations(this.xml("MultiClientRegistration-WithCustomGrantedAuthorities")).autowire();
    Map<String, Object> attributes = new HashMap<>();
    attributes.put(OAuth2ParameterNames.REGISTRATION_ID, "github-login");
    OAuth2AuthorizationRequest authorizationRequest = TestOAuth2AuthorizationRequests.request().attributes(attributes).build();
    given(this.authorizationRequestRepository.removeAuthorizationRequest(any(), any())).willReturn(authorizationRequest);
    OAuth2AccessTokenResponse accessTokenResponse = TestOAuth2AccessTokenResponses.accessTokenResponse().build();
    given(this.accessTokenResponseClient.getTokenResponse(any())).willReturn(accessTokenResponse);
    OAuth2User oauth2User = TestOAuth2Users.create();
    given(this.oauth2UserService.loadUser(any())).willReturn(oauth2User);
    given(this.userAuthoritiesMapper.mapAuthorities(any())).willReturn((Collection) AuthorityUtils.createAuthorityList("ROLE_OAUTH2_USER"));
    MultiValueMap<String, String> params = new LinkedMultiValueMap<>();
    params.add("code", "code123");
    params.add("state", authorizationRequest.getState());
    this.mvc.perform(get("/login/oauth2/code/github-login").params(params)).andExpect(status().is2xxSuccessful());
    ArgumentCaptor<Authentication> authenticationCaptor = ArgumentCaptor.forClass(Authentication.class);
    verify(this.authenticationSuccessHandler).onAuthenticationSuccess(any(), any(), authenticationCaptor.capture());
    Authentication authentication = authenticationCaptor.getValue();
    assertThat(authentication.getPrincipal()).isInstanceOf(OAuth2User.class);
    assertThat(authentication.getAuthorities()).hasSize(1);
    assertThat(authentication.getAuthorities()).first().isInstanceOf(SimpleGrantedAuthority.class).hasToString("ROLE_OAUTH2_USER");
    // re-setup for OIDC test
    attributes = new HashMap<>();
    attributes.put(OAuth2ParameterNames.REGISTRATION_ID, "google-login");
    authorizationRequest = TestOAuth2AuthorizationRequests.oidcRequest().attributes(attributes).build();
    given(this.authorizationRequestRepository.removeAuthorizationRequest(any(), any())).willReturn(authorizationRequest);
    accessTokenResponse = TestOAuth2AccessTokenResponses.oidcAccessTokenResponse().build();
    given(this.accessTokenResponseClient.getTokenResponse(any())).willReturn(accessTokenResponse);
    Jwt jwt = TestJwts.user();
    given(this.jwtDecoderFactory.createDecoder(any())).willReturn((token) -> jwt);
    given(this.userAuthoritiesMapper.mapAuthorities(any())).willReturn((Collection) AuthorityUtils.createAuthorityList("ROLE_OIDC_USER"));
    // @formatter:off
    this.mvc.perform(get("/login/oauth2/code/google-login").params(params)).andExpect(status().is2xxSuccessful());
    // @formatter:on
    authenticationCaptor = ArgumentCaptor.forClass(Authentication.class);
    verify(this.authenticationSuccessHandler, times(2)).onAuthenticationSuccess(any(), any(), authenticationCaptor.capture());
    authentication = authenticationCaptor.getValue();
    assertThat(authentication.getPrincipal()).isInstanceOf(OidcUser.class);
    assertThat(authentication.getAuthorities()).hasSize(1);
    assertThat(authentication.getAuthorities()).first().isInstanceOf(SimpleGrantedAuthority.class).hasToString("ROLE_OIDC_USER");
}
Also used : OAuth2AccessTokenResponse(org.springframework.security.oauth2.core.endpoint.OAuth2AccessTokenResponse) OAuth2User(org.springframework.security.oauth2.core.user.OAuth2User) HashMap(java.util.HashMap) LinkedMultiValueMap(org.springframework.util.LinkedMultiValueMap) Jwt(org.springframework.security.oauth2.jwt.Jwt) SimpleGrantedAuthority(org.springframework.security.core.authority.SimpleGrantedAuthority) Authentication(org.springframework.security.core.Authentication) OAuth2AuthorizationRequest(org.springframework.security.oauth2.core.endpoint.OAuth2AuthorizationRequest) Test(org.junit.jupiter.api.Test)

Example 84 with JWT

use of com.auth0.jwt.JWT in project c4sg-services by Code4SocialGood.

the class JwtUtil method match.

/**
 * Checks if the email matches
 * @param email Email address
 * @return True if match
 */
public static boolean match(String email) {
    AuthenticationJsonWebToken auth = (AuthenticationJsonWebToken) SecurityContextHolder.getContext().getAuthentication();
    if (auth != null) {
        DecodedJWT jwt = (DecodedJWT) auth.getDetails();
        String emailFromClaim = jwt.getClaim("http://email").asString();
        if (email.equals(emailFromClaim))
            return true;
    }
    return false;
}
Also used : AuthenticationJsonWebToken(com.auth0.spring.security.api.authentication.AuthenticationJsonWebToken) DecodedJWT(com.auth0.jwt.interfaces.DecodedJWT)

Example 85 with JWT

use of com.auth0.jwt.JWT in project dhis2-core by dhis2.

the class JwtBearerTokenTest method testJwkEncodeEndDecode.

@Test
void testJwkEncodeEndDecode() throws JOSEException {
    Jwt encodedJws = createJwt(TEST_PROVIDER_ONE_URI, CLIENT_ID_1, DEFAULT_MAPPING_CLAIM, DEFAULT_EMAIL);
    assertEquals("JWT", encodedJws.getHeaders().get(JoseHeaderNames.TYP));
    assertEquals(RSA_KEY.getKeyID(), encodedJws.getHeaders().get(JoseHeaderNames.KID));
    assertNotNull(encodedJws.getId());
    String tokenValue = encodedJws.getTokenValue();
    jwtDecoder.decode(tokenValue);
}
Also used : Jwt(org.springframework.security.oauth2.jwt.Jwt) DhisControllerWithJwtTokenAuthTest(org.hisp.dhis.webapi.DhisControllerWithJwtTokenAuthTest) Test(org.junit.jupiter.api.Test)

Aggregations

Jwt (org.springframework.security.oauth2.jwt.Jwt)99 Test (org.junit.jupiter.api.Test)80 GrantedAuthority (org.springframework.security.core.GrantedAuthority)51 SimpleGrantedAuthority (org.springframework.security.core.authority.SimpleGrantedAuthority)39 DecodedJWT (com.auth0.jwt.interfaces.DecodedJWT)23 Assertions.assertThat (org.assertj.core.api.Assertions.assertThat)19 Arrays (java.util.Arrays)18 ClientRegistration (org.springframework.security.oauth2.client.registration.ClientRegistration)18 TestJwts (org.springframework.security.oauth2.jwt.TestJwts)18 List (java.util.List)17 Algorithm (com.auth0.jwt.algorithms.Algorithm)16 AbstractAuthenticationToken (org.springframework.security.authentication.AbstractAuthenticationToken)16 Authentication (org.springframework.security.core.Authentication)16 Test (org.junit.Test)14 HashMap (java.util.HashMap)13 OAuth2AccessTokenResponse (org.springframework.security.oauth2.core.endpoint.OAuth2AccessTokenResponse)13 Instant (java.time.Instant)11 Assertions.assertThatIllegalArgumentException (org.assertj.core.api.Assertions.assertThatIllegalArgumentException)11 BeforeEach (org.junit.jupiter.api.BeforeEach)11 JWTVerifier (com.auth0.jwt.JWTVerifier)10