java - getting 401 to access http:localhost:8080oauthtoken - Stack Overflow

I am hitting one end point from my angularjs client app to login when I am doing that one I am getting

I am hitting one end point from my angularjs client app to login when I am doing that one I am getting the following ERROR in browser console

OPTIONS http://localhost:8080/oauth/token XMLHttpRequest cannot load http://localhost:8080/oauth/token. Invalid HTTP status code 401

It's server side code to accept CORS from the client.

@Component
public class SimpleCORSFilter implements Filter {

	public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException {
		HttpServletResponse response = (HttpServletResponse) res;
		response.setHeader("Access-Control-Allow-Origin", "*");
		response.setHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS, DELETE");
		response.setHeader("Access-Control-Max-Age", "3600");
		response.setHeader("Access-Control-Allow-Headers", "x-requested-with");
		chain.doFilter(req, res);
	}

	public void init(FilterConfig filterConfig) {}

	public void destroy() {}

}

I am hitting one end point from my angularjs client app to login when I am doing that one I am getting the following ERROR in browser console

OPTIONS http://localhost:8080/oauth/token XMLHttpRequest cannot load http://localhost:8080/oauth/token. Invalid HTTP status code 401

It's server side code to accept CORS from the client.

@Component
public class SimpleCORSFilter implements Filter {

	public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException {
		HttpServletResponse response = (HttpServletResponse) res;
		response.setHeader("Access-Control-Allow-Origin", "*");
		response.setHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS, DELETE");
		response.setHeader("Access-Control-Max-Age", "3600");
		response.setHeader("Access-Control-Allow-Headers", "x-requested-with");
		chain.doFilter(req, res);
	}

	public void init(FilterConfig filterConfig) {}

	public void destroy() {}

}

It's client side code which calling the http://localhost:8080/oauth/token

angular.module('frontendApp')
  .factory('AuthServerProvider', function loginService($http, localStorageService, Base64, API_SERVER) {
    return {
      login: function (credentials) {
        var data = "username=" + credentials.username + "&password="
          + credentials.password + "&grant_type=password&scope=read%20write&" +
          "client_secret=123456&client_id=clientapp";
        return $http.post(API_SERVER + 'oauth/token', data, {
          headers: {
            "Content-Type": "application/x-www-form-urlencoded",
            "Accept": "application/json",
            "Access-Control-Allow-Origin": "*",
            "Authorization": "Basic " + Base64.encode("clientapp" + ':' + "123456")
          }
        }).success(function (response) {
          var expiredAt = new Date();
          expiredAt.setSeconds(expiredAt.getSeconds() + response.expires_in);
          response.expires_at = expiredAt.getTime();
          localStorageService.set('token', response);
          return response;
        });
      },
      logout: function () {
        // logout from the server
        $http.post('api/logout').then(function () {
          localStorageService.clearAll();
        });
      },
      getToken: function () {
        return localStorageService.get('token');
      },
      hasValidToken: function () {
        var token = this.getToken();
        return token && token.expires_at && token.expires_at > new Date().getTime();
      }
    };
  });

Share Improve this question edited Jun 21, 2015 at 9:50 Brian Tompsett - 汤莱恩 5,89372 gold badges61 silver badges133 bronze badges asked Jun 21, 2015 at 9:42 karthik pamidimarrikarthik pamidimarri 3052 silver badges12 bronze badges 4
  • You add the url oauth/auth to anonymous permission in Spring? – Jesús Quintana Commented Jun 21, 2015 at 9:45
  • Add 'Authorization' header to the Access-Control-Allow-Headers list – Michael Commented Jun 21, 2015 at 10:21
  • @Michael I already added in the code these Access-Control-Allow-Headers list please see once, my credentials are not adding to request when i seen in browser console in the network. – karthik pamidimarri Commented Jun 21, 2015 at 10:34
  • The OPTION request was sent from the browser to check access permission - not from angular. Not sure about the solution, but you should google for CORS with credentials – Michael Commented Jun 21, 2015 at 10:40
Add a ment  | 

2 Answers 2

Reset to default 5

In case of OPTIONS request, you should not do further processing, i.e. skip the call to chain.doFilter(req, res), e.g.:

    HttpServletRequest request = (HttpServletRequest) req;
    HttpServletResponse response = (HttpServletResponse) resp;

    response.addHeader("Access-Control-Allow-Origin", "*");

    if ("OPTIONS".equalsIgnoreCase(request.getMethod())) {
        response.setHeader("Access-Control-Allow-Methods", "POST,GET,DELETE");
        response.setHeader("Access-Control-Max-Age", "3600");
        response.setHeader("Access-Control-Allow-Headers", "content-type,access-control-request-headers,access-control-request-method,accept,origin,authorization,x-requested-with");
        response.setStatus(HttpServletResponse.SC_OK);
    } else {
        chain.doFilter(req, resp);
    }

For Oauth2 you will be having this configuration class which extends AuthorizationServerConfigurerAdapter. In this class you can add this code

@Configuration
@EnableAuthorizationServer
public static class AuthServerConfiguration extends AuthorizationServerConfigurerAdapter {
   

    @Override
    public void configure(AuthorizationServerSecurityConfigurer security) {
        

        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        CorsConfiguration config = new CorsConfiguration();
        config.applyPermitDefaultValues();

       AuthorizationServerEndpointsConfigurer 
        source.registerCorsConfiguration("/oauth/token", config);
        CorsFilter filter = new CorsFilter(source);
        security.addTokenEndpointAuthenticationFilter(filter);
    }
}

This will add the configs of cors for Oauth

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1745567706a4633495.html

相关推荐

  • java - getting 401 to access http:localhost:8080oauthtoken - Stack Overflow

    I am hitting one end point from my angularjs client app to login when I am doing that one I am getting

    15小时前
    40

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信