简体   繁体   English

在Spring Boot OAuth 2中无法从主体对象获取用户详细信息

[英]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;
    }
}

This is my code. 这是我的代码。 I have tried with maximum possible ways to get details of the user. 我尝试了最大可能的方式来获取用户的详细信息。 Actually i want email of the user but when I'm returning "user" -- principal object, it is giving json on the screen. 实际上我想要用户的电子邮件,但是当我返回“用户”-主要对象时,它在屏幕上给出了json。 Please help me on this.. 请帮助我。

Added spring security configuration... Please go through it and let me know if I made any thing wrong.. and my scope is openid, email, profile 添加了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;
    }
}

The problem is you haven't configure your AuthenticationManager in your code you have done this @Override protected void configure(AuthenticationManagerBuilder auth) throws Exception { super.configure(auth); } 问题是您尚未在代码中配置AuthenticationManager ,因此已完成此@Override protected void configure(AuthenticationManagerBuilder auth) throws Exception { super.configure(auth); } @Override protected void configure(AuthenticationManagerBuilder auth) throws Exception { super.configure(auth); }

Authentication Manager: 身份验证管理器:

attempts to authenticate the passed Authentication object, returning a fully populated Authentication object (including granted authorities) if successful. 尝试对传递的Authentication对象进行身份验证,如果成功,则返回完全填充的Authentication对象(包括授予的权限)。

For simple in memory Authentication Manager you can do something like this; 为了简化内存身份验证管理器,您可以执行以下操作;

@Autowired
public void configure(AuthenticationManagerBuilder auth)
        throws Exception {
    auth.inMemoryAuthentication().withUser("user").password("password")
            .roles("USER").and().withUser("hiren").password("hiren")
            .roles("ADMIN");
}

After this you can get Principal object after successful authentication of user. 此后,您可以在成功验证用户身份之后获取Principal对象。 You can also configure your own authentication provider like this: 您还可以像这样配置自己的身份验证提供程序:

@Override
protected void configure(
  AuthenticationManagerBuilder auth) throws Exception {

    auth.authenticationProvider(customeAuthenticationProvider);
}

this link will be useful for authentication provider configuration 链接对于身份验证提供程序配置很有用

Your method is a REST endpoint, meaning that the parameters coming to this function are serialized data. 您的方法是REST端点,这意味着到达此函数的参数是序列化数据。 You need to deserialize it and get the required data from it. 您需要对其进行反序列化并从中获取所需的数据。 The parameter of this function cannot be in Priciple type, from where you sent you probably need to send it in byte[] . 该函数的参数不能为Priciple类型,您从其发送的位置可能需要以byte[]发送。 Then you need to convert byte[] into String , which is a JSON. 然后,您需要将byte[]转换为String ,这是一个JSON。 Then using Jackson library you need to fill your user . 然后,使用Jackson库需要填充user After that you can obtain the e-mail of the 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.

相关问题 Spring Security:如何从委托人那里获取详细信息? - Spring Security: How to get details from the principal? Spring Boot + Google OAuth2:如何定义用户详细信息服务? - Spring Boot + Google OAuth2: how to define user details service? Spring Boot OAuth2:如何检索用户令牌信息详细信息 - Spring Boot OAuth2: How to retrieve user token info details Spring 引导安全主体用户更改为新登录的用户详细信息 - Spring boot security principal user getting changed to newly logged in user details 将权限和用户主体从 rest 客户端传递到服务器 spring 启动 - Passing authorities and user principal from rest client to server spring boot Spring 启动 Oauth 安全性 - 客户端凭据授予类型中主体中的用户(自定义信息)信息 - Spring boot Oauth security - User(custom info) info in the principal in Client Credentials grant type 从 JWT 令牌获取 Spring Boot 资源服务器中的主体 - Get principal in Spring Boot resource server from JWT token Spring 启动 oauth2:无 userInfo 端点 - 如何直接在客户端从 JWT 访问令牌加载身份验证(主体) - Spring boot oauth2: No userInfo endpoint - How to load the authentication (Principal) from the JWT access token directly in the client 从 Principal 中提取数据 Java Spring Boot - Extract data from Principal in Java Spring Boot Azure Spring Boot-获取已登录用户的OAuth 2.0访问令牌 - Azure Spring Boot - Get OAuth 2.0 Access Token of Logged In User
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM