Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Boot rest azure ad auth cc #33

Merged
merged 4 commits into from
May 1, 2020
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Prev Previous commit
Next Next commit
fully workable rest api sample
  • Loading branch information
vvoinov committed May 1, 2020
commit 9690c42d3ba20284a823550395bc4fb62d732729
Original file line number Diff line number Diff line change
@@ -1,10 +1,17 @@

package com.mogikanensoftware.greetings.api.rest;

import java.security.Principal;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import com.auth0.jwt.interfaces.Claim;
import com.mogikanensoftware.greetings.api.token.Auth0Parser;

import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.core.context.SecurityContext;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.oauth2.provider.OAuth2Authentication;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
Expand All @@ -17,28 +24,47 @@
@Slf4j
public class GreetingController {

@GetMapping("/whoami")
public String whoami(OAuth2Authentication authentication) {
log.info("authentication -> {}", authentication);
Object principal = SecurityContextHolder.getContext().getAuthentication().getPrincipal();
log.info("principal -> {}", principal);
return (String)principal;
}

@PreAuthorize("hasAuthority('SCOPE_CallHiApiRole')")
@GetMapping("/hi")
public String hi(final Principal principal) {
log.info("hi endpoint is beeing called and principal is -> {}", principal);
public String hi() {
return "Hi";
}

@PreAuthorize("hasAuthority('SCOPE_CallHelloApiRole')")
@GetMapping("/hello")
public String hello(@RequestParam(name = "name", required = true)
final String name) {
log.info("hello endpoint is beeing called with name param {}", name);
return String.format("Hello, %s", name);
}

Object principal = SecurityContextHolder.getContext().getAuthentication().getPrincipal();
log.info("hello#principal -> {}", principal);
@GetMapping("/whoami")
public String whoami(HttpServletRequest request) {

// Get security context and print authorities
SecurityContext securityContext = SecurityContextHolder.getContext();
log.info("whoami: securityContext.getAuthentication-> {}", securityContext.getAuthentication());
securityContext.getAuthentication().getAuthorities().stream().forEach(
(val) -> log.info("Authority->{}", val.getAuthority()));

// Get token value from the header
String authHeaderValue = request.getHeader("Authorization");
log.debug("authHeaderValue: {}", authHeaderValue);

String appId = "undefined";

if (!StringUtils.isEmpty(authHeaderValue)) {
String token = request.getHeader("Authorization").replaceAll("Bearer ", "");
log.debug("token: {}", token);

// Access all claims from the token itself by using Auth0 JWT impl
Map <String, Claim> claims = new Auth0Parser().getClaims(token);
if (!claims.isEmpty()) {
claims.get("roles").asList(String.class).forEach(role -> log.info(role));
appId = claims.get("appid").asString();
}
}

return appId;

return String.format("Hello, %s", name);
}
}
Original file line number Diff line number Diff line change
@@ -1,30 +1,51 @@

package com.mogikanensoftware.greetings.api.security;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.oauth2.config.annotation.web.configuration.EnableResourceServer;
import org.springframework.security.oauth2.config.annotation.web.configuration.ResourceServerConfigurerAdapter;
import org.springframework.security.oauth2.config.annotation.web.configurers.ResourceServerSecurityConfigurer;
import org.springframework.security.oauth2.server.resource.authentication.JwtAuthenticationConverter;
import org.springframework.security.oauth2.server.resource.authentication.JwtGrantedAuthoritiesConverter;

@Configuration
@EnableResourceServer
@EnableWebSecurity
public class ResourceServerConfig extends ResourceServerConfigurerAdapter {

@Value("${security.oauth2.resource.jwk.key-set-uri}")
protected String jwkSetUri;

@Value("${security.oauth2.resource.id}")
protected String apiUri;

@Override
public void configure(ResourceServerSecurityConfigurer resources) throws Exception {
resources.resourceId("api://a450c6a3-bb9e-42fd-8650-3aa064c99816");
public void configure(final ResourceServerSecurityConfigurer resources) throws Exception {
resources.resourceId(apiUri).stateless(true);
}

@Override
public void configure(HttpSecurity http) throws Exception {
http.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS)
.and()
.authorizeRequests()
.antMatchers("/api/v1/**").authenticated()
.antMatchers("/").permitAll();
public void configure(final HttpSecurity http) throws Exception {

http
.authorizeRequests(authorize -> authorize
.antMatchers("/api/v1/**").authenticated()
.antMatchers("/").permitAll())
.oauth2ResourceServer(oauth2 -> oauth2
.jwt(jwt -> jwt
.jwtAuthenticationConverter(jwtAuthenticationConverter())
.jwkSetUri(jwkSetUri)));
}

private JwtAuthenticationConverter jwtAuthenticationConverter() {
JwtGrantedAuthoritiesConverter grantedAuthoritiesConverter = new JwtGrantedAuthoritiesConverter();
grantedAuthoritiesConverter.setAuthoritiesClaimName("roles");

JwtAuthenticationConverter jwtAuthenticationConverter = new JwtAuthenticationConverter();
jwtAuthenticationConverter.setJwtGrantedAuthoritiesConverter(grantedAuthoritiesConverter);
return jwtAuthenticationConverter;
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@

package com.mogikanensoftware.greetings.api.token;

import java.util.Map;

import com.auth0.jwt.JWT;
import com.auth0.jwt.interfaces.Claim;
import com.auth0.jwt.interfaces.DecodedJWT;

import lombok.extern.slf4j.Slf4j;

@Slf4j
public class Auth0Parser {

public Map <String, Claim> getClaims(String accessToken) {

log.debug("getClaims(): accessToken-> {}",accessToken);

DecodedJWT decoded = JWT.decode(accessToken);

Map <String, Claim> claims = decoded.getClaims();

log.debug("getClaims(): claims-> {}",claims);

return claims;
}

}