[英]Not able to get user details from principal object in Spring boot OAuth 2
@RestController
public class AuthenticationController {
@RequestMapping("/")
protected Principal login(Principal user) {
ObjectMapper mapper = new ObjectMapper();
System.out.println(SecurityContextHolder.getContext().getAuthentication().getPrincipal());
System.out.println(SecurityContextHolder.getContext().getAuthentication().getDetails());
System.out.println(SecurityContextHolder.getContext().getAuthentication().getPrincipal());
System.out.println("testing testing xyz");
return user;
}
}
這是我的代碼。 我嘗試了最大可能的方式來獲取用戶的詳細信息。 實際上我想要用戶的電子郵件,但是當我返回“用戶”-主要對象時,它在屏幕上給出了json。 請幫助我。
添加了spring安全配置...請仔細檢查,如果我做錯了任何事,請讓我知道。我的范圍是openid,電子郵件,個人資料
package com.ggktech;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Configurable;
import org.springframework.boot.autoconfigure.security.oauth2.resource.ResourceServerProperties;
import org.springframework.boot.autoconfigure.security.oauth2.resource.UserInfoTokenServices;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.builders.WebSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.oauth2.client.OAuth2ClientContext;
import org.springframework.security.oauth2.client.OAuth2RestTemplate;
import org.springframework.security.oauth2.client.filter.OAuth2ClientAuthenticationProcessingFilter;
import org.springframework.security.oauth2.client.token.grant.code.AuthorizationCodeResourceDetails;
import org.springframework.security.web.authentication.www.BasicAuthenticationFilter;
import org.springframework.security.web.csrf.CookieCsrfTokenRepository;
/**
* Modifying or overriding the default spring boot security.
*/
@Configurable
@EnableWebSecurity
public class OAuthSecurityConfig extends WebSecurityConfigurerAdapter {
private OAuth2ClientContext oauth2ClientContext;
private AuthorizationCodeResourceDetails authorizationCodeResourceDetails;
private ResourceServerProperties resourceServerProperties;
@Autowired
public void setOauth2ClientContext(OAuth2ClientContext oauth2ClientContext) {
this.oauth2ClientContext = oauth2ClientContext;
}
@Autowired
public void setAuthorizationCodeResourceDetails(AuthorizationCodeResourceDetails authorizationCodeResourceDetails) {
this.authorizationCodeResourceDetails = authorizationCodeResourceDetails;
}
@Autowired
public void setResourceServerProperties(ResourceServerProperties resourceServerProperties) {
this.resourceServerProperties = resourceServerProperties;
}
/* This method is for overriding the default AuthenticationManagerBuilder.
We can specify how the user details are kept in the application. It may
be in a database, LDAP or in memory.*/
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
super.configure(auth);
}
/* This method is for overriding some configuration of the WebSecurity
If you want to ignore some request or request patterns then you can
specify that inside this method.*/
@Override
public void configure(WebSecurity web) throws Exception {
super.configure(web);
}
/*This method is used for override HttpSecurity of the web Application.
We can specify our authorization criteria inside this method.*/
@Override
protected void configure(HttpSecurity http) throws Exception {
http
// Starts authorizing configurations.
.authorizeRequests()
// Ignore the "/" and "/index.html"
.antMatchers("/", "/**.html", "/**.js").permitAll()
// Authenticate all remaining URLs.
.anyRequest().fullyAuthenticated()
.and()
// Setting the logout URL "/logout" - default logout URL.
.logout()
// After successful logout the application will redirect to "/" path.
.logoutSuccessUrl("/")
.permitAll()
.and()
// Setting the filter for the URL "/google/login".
.addFilterAt(filter(), BasicAuthenticationFilter.class)
.csrf()
.csrfTokenRepository(CookieCsrfTokenRepository.withHttpOnlyFalse());
}
/*This method for creating filter for OAuth authentication.*/
private OAuth2ClientAuthenticationProcessingFilter filter() {
//Creating the filter for "/google/login" url
OAuth2ClientAuthenticationProcessingFilter oAuth2Filter = new OAuth2ClientAuthenticationProcessingFilter(
"/login");
//Creating the rest template for getting connected with OAuth service.
//The configuration parameters will inject while creating the bean.
OAuth2RestTemplate oAuth2RestTemplate = new OAuth2RestTemplate(authorizationCodeResourceDetails,
oauth2ClientContext);
oAuth2Filter.setRestTemplate(oAuth2RestTemplate);
// Setting the token service. It will help for getting the token and
// user details from the OAuth Service.
oAuth2Filter.setTokenServices(new UserInfoTokenServices(resourceServerProperties.getUserInfoUri(),
resourceServerProperties.getClientId()));
return oAuth2Filter;
}
}
問題是您尚未在代碼中配置AuthenticationManager
,因此已完成此@Override protected void configure(AuthenticationManagerBuilder auth) throws Exception { super.configure(auth); }
@Override protected void configure(AuthenticationManagerBuilder auth) throws Exception { super.configure(auth); }
身份驗證管理器:
嘗試對傳遞的Authentication對象進行身份驗證,如果成功,則返回完全填充的Authentication對象(包括授予的權限)。
為了簡化內存身份驗證管理器,您可以執行以下操作;
@Autowired
public void configure(AuthenticationManagerBuilder auth)
throws Exception {
auth.inMemoryAuthentication().withUser("user").password("password")
.roles("USER").and().withUser("hiren").password("hiren")
.roles("ADMIN");
}
此后,您可以在成功驗證用戶身份之后獲取Principal
對象。 您還可以像這樣配置自己的身份驗證提供程序:
@Override
protected void configure(
AuthenticationManagerBuilder auth) throws Exception {
auth.authenticationProvider(customeAuthenticationProvider);
}
此鏈接對於身份驗證提供程序配置很有用
您的方法是REST端點,這意味着到達此函數的參數是序列化數據。 您需要對其進行反序列化並從中獲取所需的數據。 該函數的參數不能為Priciple
類型,您從其發送的位置可能需要以byte[]
發送。 然后,您需要將byte[]
轉換為String
,這是一個JSON。 然后,使用Jackson
庫需要填充user
。 之后,您可以獲得用戶的電子郵件。
@RequestMapping("/")
protected Principal login(byte[] data) {
String inputJSONString = new String(data);
ObjectMapper mapper = new ObjectMapper();
Principle user = objectMapper.readValue(inputJSONString, Principle.class);
//Now you have a setted user object and you can get user's mail from a method like getMail()
user.getMail();
System.out.println(SecurityContextHolder.getContext().getAuthentication().getPrincipal());
System.out.println(SecurityContextHolder.getContext().getAuthentication().getDetails());
System.out.println(SecurityContextHolder.getContext().getAuthentication().getPrincipal(
System.out.println("testing testing xyz");
return user;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.