I have Spring Boot app that uses OAuth 2.0 and Authorization Server. When I try to access secured page, I got redirect on login page of my authorization server (Blitz Identity Provider) and everything works great here like it should. My problem is that I can't extract authorization token in @Controller (on secured page). That token I want to use later to authorize in second application.
Here are 2 files which can help you to understand some part of my context.
application.yml
server:
port: 8080
context-path: /
session:
cookie:
name:FIRSTSESSION
security:
basic:
enabled: false
oauth2:
client:
clientId: test_id
clientSecret: f3M5m9a2Dn0v15l
accessTokenUri: http://server:9000/blitz/oauth/te
userAuthorizationUri: http://server:9000/blitz/oauth/ae?scope=test_scope
resource:
userInfoUri: http://server:9000/blitz/oauth/me
logging:
level:
org.springframework.security: DEBUG
SsoController.java
@EnableOAuth2Sso
@Controller
public class SsoController {
@RequestMapping("/secondService")
public String getContent(HttpServletRequest request, Model model) {
Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
model.addAttribute("submittedValue", authentication.getDetails());
return "secondService";
}
}
So, what you can suggest? How can I extract authorization token in this case?
To get a token to call the downstream API, you inject the ITokenAcquisition service by dependency injection in your controller's constructor (or your page constructor if you use Blazor), and you use it in your controller actions, getting a token for the user ( GetAccessTokenForUserAsync ) or for the application itself ...
You use the POST operation on the api/get_token element to request your unique token that is required to authenticate the REST API requests. , and click Profile. Then, click Show token.
If you have configured oauth2 authorization/resource server you can try below code:
@Autowired
private TokenStore tokenStore;
@RequestMapping(method = {RequestMethod.POST, RequestMethod.GET}, value = "/oauth/me")
public Map<String, Object> userInfo(OAuth2Authentication auth){
final OAuth2AuthenticationDetails details = (OAuth2AuthenticationDetails) auth.getDetails();
//token
String accessToken = details.getTokenValue();
//reference
final OAuth2AccessToken accessToken = tokenStore.readAccessToken(details.getTokenValue());
// clientid
String clientId = auth.getOAuth2Request().getClientId();
}
Hope it helps!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With