Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

I try to access my Spring-Boot-application with Oauth2-Authentication with angular2. When i send a post-request to "oauth/token" with my basic authentication including username and password to get a token, which works fine in postman, i get an 401 Unauthorized. I know that my browser sends a preflight-request with the OPTIONS-method, and i have implemented my security-configuration so that it should ignore and allow the options request, but it doesnt work.

Here is my security-configuration:

@Configuration
@EnableGlobalMethodSecurity(prePostEnabled = true)
@EnableWebSecurity
@Order(SecurityProperties.ACCESS_OVERRIDE_ORDER)
public class OAuth2SecurityConfiguration extends WebSecurityConfigurerAdapter {

    @Autowired
    private ClientDetailsService clientDetailsService;

    @Autowired
    DataSource dataSource;

    @Autowired
    public void globalUserDetails(AuthenticationManagerBuilder auth) throws Exception {
    auth.jdbcAuthentication().dataSource(dataSource)
      .usersByUsernameQuery(
       "select username, password, 1 from users where username = ?") 
      .authoritiesByUsernameQuery(
       "select u.username, r.name from users u, roles r, role_users ru "
       + "where u.username = ? and u.id =  ru.users_id  and ru.roles_id = r.id ");
       auth.inMemoryAuthentication()
       .withUser("admin").password("admin").roles("ADMIN");
    }
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http
        .csrf().disable()
        .anonymous().disable()
        .authorizeRequests()
        .antMatchers(HttpMethod.OPTIONS, "/oauth/token").permitAll();

    }
    @Override
    public void configure(WebSecurity web) throws Exception {
        web.ignoring().antMatchers(HttpMethod.OPTIONS,"/oauth/token");
    }

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

Especially the last configure-method should allow me to access the api and get a token.

What could be the problem? Thanks for all help.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
226 views
Welcome To Ask or Share your Answers For Others

1 Answer

I found the problem....the problem was me.

There is nothing wrong on this code. i just started the wrong server (copy project). Everything works fine.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...