These are chat archives for spring-guides/tut-spring-security-and-angular-js

10th
Jul 2015
Pamidimarri
@Pamidimarri
Jul 10 2015 06:14
Hi Dyser , here is my code for fetching the Logged in user details and I am printing the GrantedAuthorities It's going to infinite loop and giving error message
public class JdbcUserDetailsService implements UserDetailsService {
@Autowired
private UserRepository userRepository;

@Override
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
    Optional<de.frontierpsychiatrist.example.oauth.domain.User> userfromdb = userRepository
            .findOneByLogin(username);
    if (userfromdb == null) {
        throw new UsernameNotFoundException("User " + username + " not found in database.");
    }
    de.frontierpsychiatrist.example.oauth.domain.User user = userfromdb.get();
    // return new User(user.getLogin(), user.getPassword(),
    // user.isActivated(), true, true, true, user.getAuthorities());

    // return new UserRepositoryUserDetails(user);
    List<GrantedAuthority> grantedAuthorities = user.getAuthorities().stream()
            .map(authority -> new SimpleGrantedAuthority(authority.getName())).collect(Collectors.toList());
    System.out.println("Granted authoriteis are" + grantedAuthorities);

    return new org.springframework.security.core.userdetails.User(username, user.getPassword(),user.isActivated(),true,true,true, grantedAuthorities);
}
Dave Syer
@dsyer
Jul 10 2015 06:20
That's nothing to do with the error from yesterday right? That class is not in the loop.
Pamidimarri
@Pamidimarri
Jul 10 2015 06:21
yes
Please check this class

@Configuration
@EnableAuthorizationServer
@Lazy
public class OAuthConfiguration extends AuthorizationServerConfigurerAdapter {
@Autowired
private AuthenticationManager authenticationManager;

@Bean
@ConfigurationProperties(prefix = "spring.datasource_oauth")
public DataSource oauthDataSource() {
    return DataSourceBuilder.create().build();
}

/**
 * We expose the JdbcClientDetailsService because it has extra methods that
 * the Interface does not have. E.g.
 * {@link org.springframework.security.oauth2.provider.client.JdbcClientDetailsService#listClientDetails()}
 * which we need for the admin page.
 */
@Bean
public JdbcClientDetailsService clientDetailsService() {
    return new JdbcClientDetailsService(oauthDataSource());
}

@Bean

public TokenStore tokenStore() {
    return new JdbcTokenStore(oauthDataSource());
}

@Bean
public ApprovalStore approvalStore() {
    return new JdbcApprovalStore(oauthDataSource());
}

@Bean
public AuthorizationCodeServices authorizationCodeServices() {

    return new JdbcAuthorizationCodeServices(oauthDataSource());
}

@Override
public void configure(ClientDetailsServiceConfigurer clients)
        throws Exception {
    clients.withClientDetails(clientDetailsService());
}

@Override
public void configure(AuthorizationServerSecurityConfigurer oauthServer)
        throws Exception {

}

@Override
public void configure(AuthorizationServerEndpointsConfigurer endpoints)
        throws Exception {
    endpoints.approvalStore(approvalStore())
            .authorizationCodeServices(authorizationCodeServices())
            .tokenStore(tokenStore())
            .authenticationManager(authenticationManager);
}

}

this may causing the problem?

@Configuration
@EnableWebSecurity
public class SecurityConfiguration extends WebSecurityConfigurerAdapter {

@Bean
@Override
protected UserDetailsService userDetailsService() {
    return new JdbcUserDetailsService();
}

@Override
public void configure(WebSecurity web) throws Exception {
    web.ignoring().antMatchers("/webjars/**");
}

@Override
protected void configure(HttpSecurity http) throws Exception {
    http.csrf().disable()
        .authorizeRequests()
            .antMatchers("/login", "/logout.do").permitAll()
            .antMatchers("/**").authenticated()
        .and()
        .formLogin()
            .loginProcessingUrl("/login.do")
            .usernameParameter("name")
            .loginPage("/login")
        .and()
        .logout()
            //To match GET requests we have to use a request matcher.
            .logoutRequestMatcher(new AntPathRequestMatcher("/logout.do"))
        .and()
        .userDetailsService(userDetailsService());
}

@Override
@Bean
public AuthenticationManager authenticationManagerBean() throws Exception {
    return super.authenticationManagerBean();
}

}

In these classes only I am changing the code to fetch the token info
Dave Syer
@dsyer
Jul 10 2015 06:24
You can use fences "```" to surround source code snippets
Pamidimarri
@Pamidimarri
Jul 10 2015 06:25
Ok sure
Dave Syer
@dsyer
Jul 10 2015 06:28
None of that has an @Autowired method with an AuthenticationManagerBuilder
So I can't see how your AM is being configured. How does it know about your user details?
Pamidimarri
@Pamidimarri
Jul 10 2015 06:54
Hi dsyer I implemented AuthenticationManagerBuilder from the login page I am able to login,but while I am fetching token through Postman it's saying bad credentials
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.userDetailsService(userDetailsService());
}
Dave Syer
@dsyer
Jul 10 2015 06:57
Yeah but that only applies to the filter chain with the login page
I thought you said you were going to try the @Autowired thing
Pamidimarri
@Pamidimarri
Jul 10 2015 07:00
When I done with @autowired the UserDetailsService you can't do autowire this class so I used the as bean
Now the loop issue is resolved
Dave Syer
@dsyer
Jul 10 2015 07:02
I didn't follow that. But I'm glad at least one issue is resolved.
Pamidimarri
@Pamidimarri
Jul 10 2015 07:02
Yeah thanks
Dave Syer
@dsyer
Jul 10 2015 07:03
If you want to do password grants you have to have an AuthenticationManager with your user details. It doesn't matter where it comes from.
Pamidimarri
@Pamidimarri
Jul 10 2015 07:03
but If the user doesn't have roles,If other user is not activated It's giving response to that particular scenarios
But giving response bad credentials if I entered proper username and pasword
Pamidimarri
@Pamidimarri
Jul 10 2015 07:29
Hi Dsyer,When I requested http://localhost:80801/oauth/token the response is coming as
{
"error": "invalid_grant",
"error_description": "Bad credentials"
}
Pamidimarri
@Pamidimarri
Jul 10 2015 07:35
The curl which I am requesting
curl -X POST -vu clientapp:123456 http://localhost:8081/oauth/token -H "Accept: application/json" -d "password=spring&username=criag&grant_type=password&scope=read%20write&client_secret=123456&client_id=clientapp"
The curl which I am requesting as curl -X POST -vu clientapp:123456 http://localhost:8081/oauth/token -H "Accept: application/json" -d "password=spring&username=criag&grant_type=password&scope=read%20write&client_secret=123456&client_id=clientapp"
Dave Syer
@dsyer
Jul 10 2015 07:39
I assume that's because the AM in your endpoint is the wrong one. But since I haven't seen your code (it's a moving target and you only ever paste snippets or links to other people's code) it's impossible to say why.
Pamidimarri
@Pamidimarri
Jul 10 2015 07:42
How to share my code
Dave Syer
@dsyer
Jul 10 2015 07:47
GitHub works
Please check the code
Dave Syer
@dsyer
Jul 10 2015 10:17
Where's your @Autowired AMB?
And replace it with a public void @Autowired.
That way you will be configuring the global AuthenticationManager not the local one
Pamidimarri
@Pamidimarri
Jul 10 2015 10:30
Can you explain the last suggestion
It is the global one you inject into the oauth endpoints here:""
That's how you configure the global AM
Except in your case you just copy the method not the whole class, and use your own UserDetailsService not the in memory one
"It is the global one you inject" because there is only one AM that can be @Autowired like you do in your OAuthConfiguration
Pamidimarri
@Pamidimarri
Jul 10 2015 10:48
Why two times Configure Oauth end points
Pamidimarri
@Pamidimarri
Jul 10 2015 10:54
I made change as you suggested at this line --> https://github.com/karthikpamidimarri/oauth-test/blob/master/src/main/java/de/frontierpsychiatrist/example/oauth/SecurityConfiguration.java#L63 and getting the following error
Caused by: org.springframework.beans.factory.BeanCreationException: Could not autowire method: public void org.springframework.security.config.annotation.web.configuration.WebSecurityConfiguration.setFilterChainProxySecurityConfigurer(org.springframework.security.config.annotation.ObjectPostProcessor,java.util.List) throws java.lang.Exception; nested exception is org.springframework.beans.factory.BeanExpressionException: Expression parsing failed; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'securityConfiguration': Injection of autowired dependencies failed; nested exception is java.lang.IllegalStateException: Cannot apply org.springframework.security.config.annotation.authentication.configurers.userdetails.DaoAuthenticationConfigurer@110b7 to already built object
Dave Syer
@dsyer
Jul 10 2015 10:55
I can't see your change
Pamidimarri
@Pamidimarri
Jul 10 2015 10:56
one min
I made locally I will commit
commit is done
Dave Syer
@dsyer
Jul 10 2015 11:05
It's possible you need to remove the @EnableWebSecurity (messes with Spring Boot)
Also might be a good idea to put your AM config in a separate class (can be nested if you like)
Pamidimarri
@Pamidimarri
Jul 10 2015 11:11
Just I will check
Dave Syer
@dsyer
Jul 10 2015 11:14
If you can merge your sample into one project and make it work with an embedded database I'll try it out for you.
If you don't make it really easy like that, I won't have time.
Pamidimarri
@Pamidimarri
Jul 10 2015 11:20
okay i will upload the entire project with a database file(dump file)
Dave Syer
@dsyer
Jul 10 2015 11:25
Sorry, I can't help you with that
An embedded database should work fine
I don't have a lot of time today, so messing about with mysql is not possible.
Pamidimarri
@Pamidimarri
Jul 10 2015 11:30
Ok I will add embedded database and upload the project
Pamidimarri
@Pamidimarri
Jul 10 2015 13:31
I fixed the issue Thanks for your co-operation
I fixed the issue Thanks for your co operation
Dave Syer
@dsyer
Jul 10 2015 13:39
Great. What did you do?
Pamidimarri
@Pamidimarri
Jul 10 2015 14:00
I added this code in my Security Configuration file
@Autowired
public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
auth.userDetailsService(userDetailsService());
}