首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >从数据库中自动执行Spring OAuth2

从数据库中自动执行Spring OAuth2
EN

Stack Overflow用户
提问于 2016-06-01 19:21:46
回答 1查看 152关注 0票数 2

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

curl -i --用户管理:管理-H接受:应用程序/json -X PUT http://localhost:8080/api/user/addUpdateUser -H内容类型:应用程序/json -d '{ "userId":3,"firstName":"M.Danish","lastName":"Khan","userName":"danishkhan","address":"Mardan","phone":"04543545435“}‘

代码语言:javascript
运行
复制
{
  "timestamp": 1464778621656,
  "status": 401,
  "error": "Unauthorized",
  "message": "Access Denied",
  "path": "/api/user/addUpdateUser"
}

这是我的代码。

网络安全配置

代码语言:javascript
运行
复制
@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资源服务器配置

代码语言:javascript
运行
复制
@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授权服务器配置

代码语言:javascript
运行
复制
@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;
}

}

控制器

代码语言:javascript
运行
复制
@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);
    }
}

}
EN

回答 1

Stack Overflow用户

发布于 2018-05-25 11:03:07

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

代码语言:javascript
运行
复制
-H Content-Type: application/json

应该是

代码语言:javascript
运行
复制
-H "Content-Type: application/json"

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

代码语言:javascript
运行
复制
$ curl -X POST -H "Content-Type: application/json" -H "Authorization: Bearer 27f9e2b7-4441-4c03-acdb-7e7dc358f783" -d '{"apiKey": "key", "tag": "tag"}' localhost:8080/isTagAvailable

此外,您也没有首先获得访问令牌。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/37567231

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档