io.github.jhipster.registry.security.AuthoritiesConstants Java Examples

The following examples show how to use io.github.jhipster.registry.security.AuthoritiesConstants. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: OAuth2SsoConfiguration.java    From flair-registry with Apache License 2.0 6 votes vote down vote up
@Override
protected void configure(HttpSecurity http) throws Exception {
    http
        .csrf()
        .disable()
        .headers()
        .frameOptions()
        .disable()
    .and()
        .requestMatcher(new NegatedRequestMatcher(authorizationHeaderRequestMatcher))
        .authorizeRequests()
        .antMatchers("/services/**").authenticated()
        .antMatchers("/eureka/**").hasAuthority(AuthoritiesConstants.ADMIN)
        .antMatchers("/api/profile-info").permitAll()
        .antMatchers("/api/**").authenticated()
        .antMatchers("/config/**").hasAuthority(AuthoritiesConstants.ADMIN)
        .antMatchers("/management/health").permitAll()
        .antMatchers("/management/**").hasAuthority(AuthoritiesConstants.ADMIN)
        .anyRequest().permitAll();
}
 
Example #2
Source File: OAuth2SecurityConfiguration.java    From flair-registry with Apache License 2.0 6 votes vote down vote up
@Override
public void configure(HttpSecurity http) throws Exception {
    http
        .csrf()
        .disable()
        .headers()
        .frameOptions()
        .disable()
    .and()
        .sessionManagement()
        .sessionCreationPolicy(SessionCreationPolicy.STATELESS)
    .and()
        .requestMatcher(authorizationHeaderRequestMatcher())
        .authorizeRequests()
        .antMatchers("/services/**").authenticated()
        .antMatchers("/api/profile-info").permitAll()
        .antMatchers("/api/**").authenticated()
        .antMatchers("/management/health").permitAll()
        .antMatchers("/management/**").hasAuthority(AuthoritiesConstants.ADMIN);
}
 
Example #3
Source File: AccountResourceTest.java    From flair-registry with Apache License 2.0 6 votes vote down vote up
@Test
public void testGetExistingAccount() throws Exception {

    Authentication authentication = Mockito.mock(Authentication.class);
    SecurityContext securityContext = Mockito.mock(SecurityContext.class);

    Collection authorities = new HashSet<>();
    authorities.add(new SimpleGrantedAuthority(AuthoritiesConstants.ADMIN));

    Mockito.when(securityContext.getAuthentication()).thenReturn(authentication);
    SecurityContextHolder.setContext(securityContext);
    Mockito.when(authentication.getPrincipal()).thenReturn(new User("user", "pass", authorities));
    Mockito.when(authentication.getAuthorities()).thenReturn(authorities);

    mock.perform(get("/api/account")
        .accept(MediaType.APPLICATION_JSON))
        .andExpect(status().isOk())
        .andExpect(content().contentType(MediaType.APPLICATION_JSON_UTF8_VALUE))
        .andExpect(jsonPath("$.login").value("user"))
        .andExpect(jsonPath("$.authorities").value(AuthoritiesConstants.ADMIN));
}
 
Example #4
Source File: AccountResourceTest.java    From jhipster-microservices-example with Apache License 2.0 6 votes vote down vote up
@Test
public void testGetExistingAccount() throws Exception {

    Authentication authentication = Mockito.mock(Authentication.class);
    SecurityContext securityContext = Mockito.mock(SecurityContext.class);

    Set<GrantedAuthority> authorities = new HashSet<>();
    authorities.add(new SimpleGrantedAuthority(AuthoritiesConstants.ADMIN));

    Mockito.when(securityContext.getAuthentication()).thenReturn(authentication);
    SecurityContextHolder.setContext(securityContext);
    Mockito.when(authentication.getPrincipal()).thenReturn(new User("user", "pass", authorities));

    mock.perform(get("/api/account")
        .accept(MediaType.APPLICATION_JSON))
        .andExpect(status().isOk())
        .andExpect(content().contentType(MediaType.APPLICATION_JSON_UTF8_VALUE))
        .andExpect(jsonPath("$.login").value("user"))
        .andExpect(jsonPath("$.authorities").value(AuthoritiesConstants.ADMIN));
}
 
Example #5
Source File: JWTFilterTest.java    From jhipster-registry with Apache License 2.0 6 votes vote down vote up
@Test
public void testJWTFilter() throws Exception {
    UsernamePasswordAuthenticationToken authentication = new UsernamePasswordAuthenticationToken(
        "test-user",
        "test-password",
        Collections.singletonList(new SimpleGrantedAuthority(AuthoritiesConstants.USER))
    );
    String jwt = tokenProvider.createToken(authentication, false);
    MockHttpServletRequest request = new MockHttpServletRequest();
    request.addHeader(JWTFilter.AUTHORIZATION_HEADER, "Bearer " + jwt);
    request.setRequestURI("/api/test");
    MockHttpServletResponse response = new MockHttpServletResponse();
    MockFilterChain filterChain = new MockFilterChain();
    jwtFilter.doFilter(request, response, filterChain);
    assertThat(response.getStatus()).isEqualTo(HttpStatus.OK.value());
    assertThat(SecurityContextHolder.getContext().getAuthentication().getName()).isEqualTo("test-user");
    assertThat(SecurityContextHolder.getContext().getAuthentication().getCredentials().toString()).isEqualTo(jwt);
}
 
Example #6
Source File: JWTFilterTest.java    From jhipster-registry with Apache License 2.0 6 votes vote down vote up
@Test
public void testJWTFilterWrongScheme() throws Exception {
    UsernamePasswordAuthenticationToken authentication = new UsernamePasswordAuthenticationToken(
        "test-user",
        "test-password",
        Collections.singletonList(new SimpleGrantedAuthority(AuthoritiesConstants.USER))
    );
    String jwt = tokenProvider.createToken(authentication, false);
    MockHttpServletRequest request = new MockHttpServletRequest();
    request.addHeader(JWTFilter.AUTHORIZATION_HEADER, "Basic " + jwt);
    request.setRequestURI("/api/test");
    MockHttpServletResponse response = new MockHttpServletResponse();
    MockFilterChain filterChain = new MockFilterChain();
    jwtFilter.doFilter(request, response, filterChain);
    assertThat(response.getStatus()).isEqualTo(HttpStatus.OK.value());
    assertThat(SecurityContextHolder.getContext().getAuthentication()).isNull();
}
 
Example #7
Source File: SimpleAuthoritiesExtractor.java    From flair-registry with Apache License 2.0 5 votes vote down vote up
@Override
public List<GrantedAuthority> extractAuthorities(Map<String, Object> map) {
    return Optional.ofNullable((List<String>) map.get(oauth2AuthoritiesAttribute))
        .filter(it -> !it.isEmpty())
        .orElse(Collections.singletonList(AuthoritiesConstants.USER))
        .stream()
        .map(role -> new SimpleGrantedAuthority(role))
        .collect(toList());
}
 
Example #8
Source File: JWTSecurityConfiguration.java    From flair-registry with Apache License 2.0 5 votes vote down vote up
@Override
protected void configure(HttpSecurity http) throws Exception {
    http
        .exceptionHandling()
        .authenticationEntryPoint(authenticationEntryPoint)
    .and()
        .csrf()
        .disable()
        .headers()
        .frameOptions()
        .disable()
    .and()
        .sessionManagement()
        .sessionCreationPolicy(SessionCreationPolicy.STATELESS)
     .and()
        .httpBasic()
        .realmName("JHipster Registry")
    .and()
        .authorizeRequests()
        .antMatchers("/eureka/**").hasAuthority(AuthoritiesConstants.ADMIN)
        .antMatchers("/config/**").hasAuthority(AuthoritiesConstants.ADMIN)
        .antMatchers("/api/authenticate").permitAll()
        .antMatchers("/api/profile-info").permitAll()
        .antMatchers("/api/**").authenticated()
        .antMatchers("/v2/api-docs/**").permitAll()
        .antMatchers("/swagger-resources/configuration/**").permitAll()
        .antMatchers("/swagger-ui/index.html").hasAuthority(AuthoritiesConstants.ADMIN)
        .antMatchers("/*").permitAll()
        .anyRequest().authenticated()
    .and()
        .apply(securityConfigurerAdapter());
}
 
Example #9
Source File: SecurityConfiguration.java    From jhipster-microservices-example with Apache License 2.0 5 votes vote down vote up
@Override
protected void configure(HttpSecurity http) throws Exception {
    http
        .exceptionHandling()
        .authenticationEntryPoint(authenticationEntryPoint)
    .and()
        .csrf()
        .disable()
        .headers()
        .frameOptions()
        .disable()
    .and()
        .sessionManagement()
        .sessionCreationPolicy(SessionCreationPolicy.STATELESS)
     .and()
        .httpBasic()
        .realmName("JHipster Registry")
    .and()
        .authorizeRequests()
        .antMatchers("/eureka/**").hasAuthority(AuthoritiesConstants.ADMIN)
        .antMatchers("/config/**").hasAuthority(AuthoritiesConstants.ADMIN)
        .antMatchers("/api/authenticate").permitAll()
        .antMatchers("/api/**").authenticated()
        .antMatchers("/management/**").hasAuthority(AuthoritiesConstants.ADMIN)
        .antMatchers("/*").permitAll()
        .anyRequest().authenticated()
    .and()
        .apply(securityConfigurerAdapter());
}
 
Example #10
Source File: JWTSecurityConfiguration.java    From jhipster-registry with Apache License 2.0 5 votes vote down vote up
@Override
protected void configure(HttpSecurity http) throws Exception {
    http
        .cors()
    .and()
        .exceptionHandling()
        .authenticationEntryPoint(authenticationEntryPoint)
    .and()
        .csrf()
        .disable()
        .headers()
        .frameOptions()
        .disable()
    .and()
        .sessionManagement()
        .sessionCreationPolicy(SessionCreationPolicy.STATELESS)
     .and()
        .httpBasic()
        .realmName("JHipster Registry")
    .and()
        .authorizeRequests()
        .antMatchers("/services/**").authenticated()
        .antMatchers("/eureka/**").hasAuthority(AuthoritiesConstants.ADMIN)
        .antMatchers("/config/**").hasAuthority(AuthoritiesConstants.ADMIN)
        .antMatchers("/api/authenticate").permitAll()
        .antMatchers("/api/**").hasAuthority(AuthoritiesConstants.ADMIN)
        .antMatchers("/management/info").permitAll()
        .antMatchers("/management/health").permitAll()
        .antMatchers("/management/**").hasAuthority(AuthoritiesConstants.ADMIN)
        .antMatchers("/v2/api-docs/**").permitAll()
        .antMatchers("/swagger-resources/configuration/**").permitAll()
        .antMatchers("/swagger-ui/index.html").hasAuthority(AuthoritiesConstants.ADMIN)
    .and()
        .apply(securityConfigurerAdapter());
}
 
Example #11
Source File: OAuth2SecurityConfiguration.java    From jhipster-registry with Apache License 2.0 5 votes vote down vote up
@Override
public void configure(HttpSecurity http) throws Exception {
    // @formatter:off
    http
        .cors()
    .and()
        .csrf()
        .disable()
        .headers()
        .frameOptions()
        .disable()
    .and()
        .httpBasic()
        .realmName("JHipster Registry")
    .and()
        .authorizeRequests()
        .antMatchers("/services/**").authenticated()
        .antMatchers("/eureka/**").hasAuthority(AuthoritiesConstants.ADMIN)
        .antMatchers("/config/**").hasAuthority(AuthoritiesConstants.ADMIN)
        .antMatchers("/api/**").hasAuthority(AuthoritiesConstants.ADMIN)
        .antMatchers("/management/info").permitAll()
        .antMatchers("/management/health").permitAll()
        .antMatchers("/management/**").hasAuthority(AuthoritiesConstants.ADMIN)
        .antMatchers("/v2/api-docs/**").permitAll()
        .antMatchers("/swagger-resources/configuration/**").permitAll()
        .antMatchers("/swagger-ui/index.html").hasAuthority(AuthoritiesConstants.ADMIN)
    .and()
        .oauth2Login()
    .and()
        .oauth2ResourceServer().jwt();
    // @formatter:on
}
 
Example #12
Source File: OAuth2SecurityConfiguration.java    From jhipster-registry with Apache License 2.0 5 votes vote down vote up
@Bean
@SuppressWarnings("unchecked")
public GrantedAuthoritiesMapper userAuthoritiesMapper() {
    return (authorities) -> {
        Set<GrantedAuthority> mappedAuthorities = new HashSet<>();

        authorities.forEach(authority -> {
            OidcUserInfo userInfo = null;
            // Check for OidcUserAuthority because Spring Security 5.2 returns
            // each scope as a GrantedAuthority, which we don't care about.
            if (authority instanceof OidcUserAuthority) {
                OidcUserAuthority oidcUserAuthority = (OidcUserAuthority) authority;
                userInfo = oidcUserAuthority.getUserInfo();
            }
            if (userInfo == null) {
                mappedAuthorities.add(new SimpleGrantedAuthority(AuthoritiesConstants.USER));
            } else {
                Map<String, Object> claims = userInfo.getClaims();
                Collection<String> groups = (Collection<String>) claims.getOrDefault("groups",
                    claims.getOrDefault("roles", new ArrayList<>()));

                mappedAuthorities.addAll(groups.stream()
                    .filter(group -> group.startsWith("ROLE_"))
                    .map(SimpleGrantedAuthority::new)
                    .collect(toList()));
            }
        });

        return mappedAuthorities;
    };
}
 
Example #13
Source File: AccountResourceIT.java    From jhipster-registry with Apache License 2.0 5 votes vote down vote up
@Test
@WithMockUser(username = "test", roles = "ADMIN")
public void testGetExistingAccount() throws Exception {
    mockMvc.perform(get("/api/account")
            .accept(MediaType.APPLICATION_JSON))
            .andExpect(status().isOk())
            .andExpect(content().contentType(MediaType.APPLICATION_JSON_VALUE))
            .andExpect(jsonPath("$.login").value("test"))
            .andExpect(jsonPath("$.authorities").value(AuthoritiesConstants.ADMIN));
}
 
Example #14
Source File: UaaAuthorizationHeaderUtilIT.java    From jhipster-registry with Apache License 2.0 5 votes vote down vote up
private Authentication createAuthentication() {
    return new UsernamePasswordAuthenticationToken(
        "test-user",
        "test-password",
        Collections.singletonList(new SimpleGrantedAuthority(AuthoritiesConstants.USER))
    );
}
 
Example #15
Source File: LogoutResourceIT.java    From jhipster-registry with Apache License 2.0 4 votes vote down vote up
private OAuth2AuthenticationToken authenticationToken(OidcIdToken idToken) {
    Collection<GrantedAuthority> authorities = new ArrayList<>();
    authorities.add(new SimpleGrantedAuthority(AuthoritiesConstants.USER));
    OidcUser user = new DefaultOidcUser(authorities, idToken);
    return new OAuth2AuthenticationToken(user, authorities, "oidc");
}
 
Example #16
Source File: TokenProviderTest.java    From jhipster-registry with Apache License 2.0 4 votes vote down vote up
private Authentication createAuthentication() {
    Collection<GrantedAuthority> authorities = new ArrayList<>();
    authorities.add(new SimpleGrantedAuthority(AuthoritiesConstants.ANONYMOUS));
    return new UsernamePasswordAuthenticationToken("anonymous", "anonymous", authorities);
}