如何在Rest API基本身份验证中设置Authorization标头

时间:2017-11-17 07:31:21

标签: java spring rest maven

目前我正在使用Java中的REST API。我的RestAPI是在单独的maven项目中,而Web应用程序是在单独的maven项目中。我在RestAPI中处理了基本身份验证。我想在响应标头中设置授权,并且还需要在每个请求中从HttpRequest获取它(这是最佳做法吗?)

登录应用程序后,登录用户名和密码将转发给API,如果登录凭据有效,则需要在Response中设置Authorization标头。每次我想检查标题是否有效凭证。

我的问题是,

  1. 如何设置授权标头,以及设置位置?
  2. 我想在每个回复中设置标题还是只设置一次?
  3. 我的Web.xml(RestAPI)

    <http realm="MY APP REALM">
        <csrf disabled="true" />
        <intercept-url pattern="/rest/**"
            access="hasAnyRole('ROLE_ADMIN','ROLE_USER')" />
        <http-basic entry-point-ref="basicAuthenticationEntryPoint" />
    
    </http>
    <beans:bean name="bcryptEncoder"
        class="org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder" />
    <beans:bean name="ser"
        class="com.test.api.config.SampleUserDetailsService" />
    <beans:bean name="userService" class="com.test.api.service.impl.UserServiceImpl" />
    
    <beans:bean name="basicAuthenticationEntryPoint"
        class="com.test.api.config.MyAppBasicAuthenticationEntryPoint" />
    
    
    <authentication-manager>
        <authentication-provider user-service-ref="ser">
            <password-encoder ref="bcryptEncoder" />
        </authentication-provider>
    </authentication-manager>
    

    REST API CONTROLLER

    @RestController
    @RequestMapping("/rest")
    public class RestServiceController {
    
    @Autowired
    IUserService userService;
    
    
    @RequestMapping(value = "/user", method = RequestMethod.GET)
    public ResponseEntity<List<Users>> listAllUsers() {
        List<Users> users = userService.findAllUsers();
        if (users.isEmpty()) {
            return new ResponseEntity<List<Users>>(HttpStatus.NO_CONTENT);// You many decide to return
                                                                            // HttpStatus.NOT_FOUND
        }
        return new ResponseEntity<List<Users>>(users, HttpStatus.OK);
    }
    
    }
    

    帮我解决这个问题?

2 个答案:

答案 0 :(得分:0)

查看这是否有助于您解决此问题,使用HTTPServletResponse对象打包所有内容。请参考: https://tomcat.apache.org/tomcat-8.0-doc/servletapi/javax/servlet/http/HttpServletResponse.html

response.setHeader(&#34;授权&#34;,&#34; blah&#34;);

答案 1 :(得分:0)

public class MyHandlerInterceptorAdapter extends HandlerInterceptorAdapter {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
      response.setHeader("Authorization", "token");

       return true;
    }