简体   繁体   中英

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. 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

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); } @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.

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. 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. 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[] . Then you need to convert byte[] into String , which is a JSON. Then using Jackson library you need to fill your 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;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM