【问题标题】:Spring OAuth2 autorization from database来自数据库的 Spring OAuth2 授权
【发布时间】:2018-05-25 11:03:07
【问题描述】:

大家好, 我在 Spring Boot 中练习 OAuth2。当我访问获取资源时,我已经开发了应用程序,我得到了响应,但是对于发布资源,我必须提供我在请求中传递的用户名和密码,但它仍然给了我这个回应

curl -i --user admin:admin -H Accept:application/json -X PUT http://localhost:8080/api/user/addUpdateUser -H Content-Type: application/json -d '{ "userId": 3, "firstName": "M .Danish”、“lastName”:“Khan”、“userName”:“danishkhan”、“地址”:“Mardan”、“电话”:“04543545435”}'

{
  "timestamp": 1464778621656,
  "status": 401,
  "error": "Unauthorized",
  "message": "Access Denied",
  "path": "/api/user/addUpdateUser"
}

这是我的代码。

网络安全配置

@Configuration
@EnableWebSecurity
public class WebSecurityConfiguration extends WebSecurityConfigurerAdapter{

@Autowired
private UserDetailsService userDetailsService;

@Override
public void configure(AuthenticationManagerBuilder auth) throws Exception {
    auth.userDetailsService(userDetailsService);
}

@Override
protected void configure(HttpSecurity http) throws Exception {
    http
            .authorizeRequests()
            .antMatchers(HttpMethod.GET).permitAll()
            .anyRequest().authenticated()
            .and().httpBasic()
            .and().csrf().disable();
}

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

}

OAuth 资源服务器配置

@Configuration
@EnableResourceServer
public class OAuth2ResourceServerConfiguration extends ResourceServerConfigurerAdapter {

private final String RESOURCE_ID="SpringOAuth";

@Autowired
private CustomAuthenticationEntryPoint customAuthenticationEntryPoint;

/*@Autowired
private UserDetailsService userDetailsService;*/

@Override
public void configure(HttpSecurity http) throws Exception {

    http    .exceptionHandling()
            .authenticationEntryPoint(customAuthenticationEntryPoint)
            .and()
            .authorizeRequests()
            .antMatchers(HttpMethod.GET).permitAll()
            .anyRequest().authenticated()
            /*.and().userDetailsService(userDetailsService);  was just checking whether it will work with this or not*/
}

@Override
public void configure(ResourceServerSecurityConfigurer resources) throws Exception {
    resources.resourceId(RESOURCE_ID);
}
}

OAuth 授权服务器配置

@Configuration
@EnableAuthorizationServer
public class OAuth2AuthorizationServerConfiguration extends AuthorizationServerConfigurerAdapter {

private final String RESOURCE_ID="SpringOAuth";

private TokenStore tokenStore = new InMemoryTokenStore();

@Autowired
private UserDetailsService userDetailsService;

@Autowired
AuthenticationManager authenticationManager;

@Override
public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
    clients.inMemory()
            .withClient("client")
            .authorizedGrantTypes("password", "refresh_token")
            .authorities("ROLE_USER")
            .scopes("read")
            .resourceIds(RESOURCE_ID)
            .secret("secret").accessTokenValiditySeconds(3600);
}

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



@Bean
@Primary
public DefaultTokenServices tokenServices() {
    DefaultTokenServices tokenServices = new DefaultTokenServices();
    tokenServices.setSupportRefreshToken(true);
    tokenServices.setTokenStore(this.tokenStore);
    return tokenServices;
}

}

控制器

@Controller
@RequestMapping("/api/user")
public class UserController {
@Autowired
private UserService userService;

@RequestMapping(value = "/addUpdateUser",method = RequestMethod.POST)
public ResponseEntity<Void> add_UpdateUser(@RequestBody User user){
    if(user==null){
        return new ResponseEntity<Void>(HttpStatus.EXPECTATION_FAILED);
    }else{
        userService.add_UpdateUser(user);
        return new ResponseEntity<Void>(HttpStatus.CREATED);
    }
}

@RequestMapping("/getAllUser")
public ResponseEntity<List<User>> getAllUsers(){
    return new ResponseEntity<List<User>>(userService.getAllUsers(),HttpStatus.OK);
}

@RequestMapping(value = "/deleteUser",method = RequestMethod.POST)
public ResponseEntity<Void> deleteUser(@RequestBody String userName){
    if(userName.equals("")){
        return new ResponseEntity<Void>(HttpStatus.BAD_REQUEST);
    }else {
        userService.deleteUser(userName);
        return new ResponseEntity<Void>(HttpStatus.OK);
    }
}

}

【问题讨论】:

  • 任何人请回答我的问题。我已经重新创建了应用程序,它仍然像上面描述的那样。

标签: oauth spring-boot oauth-2.0 spring-security-oauth2


【解决方案1】:

您的内容类型标题必须用引号引起来,因为您在其中有一个空格。

-H Content-Type: application/json

应该是

-H "Content-Type: application/json"

否则,shell 会将它们视为单独的参数。像这样

$ curl -X POST -H "Content-Type: application/json" -H "Authorization: Bearer 27f9e2b7-4441-4c03-acdb-7e7dc358f783" -d '{"apiKey": "key", "tag": "tag"}' localhost:8080/isTagAvailable

你也没有先获得访问令牌。

【讨论】:

    猜你喜欢
    • 2020-07-13
    • 2019-07-13
    • 1970-01-01
    • 1970-01-01
    • 2022-11-14
    • 2019-12-21
    • 1970-01-01
    • 2015-03-31
    • 2014-05-10
    相关资源
    最近更新 更多