在春季启动OAUTH2中返回RESTful/json响应而不是登录表单 [英] Return RESTful/json response instead of login form in Spring boot OAUTH2

查看:609
本文介绍了在春季启动OAUTH2中返回RESTful/json响应而不是登录表单的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在努力在用户nog登录时返回json响应,而不是返回html登录表单.

I'm struggling to return a json response when the user is nog logged in, instead of returning a html login form.

该应用程序仅使用@RestController,我不需要任何Web支持.

The application is only using @RestController's and I do not want any web support.

    http
        .authorizeRequests()
                .anyRequest().authenticated()
                .and()
                .formLogin()
                .and()
                .httpBasic().disable();

当我使用浏览器或邮递员进行获取请求时,我会收到默认的spring HTML登录表单.

When I do a get request using the browser or postman, I receive back the default spring HTML login form.

security.basic.enabled=true

我正在使用OATH2,当我请求令牌时,它工作得很好,并且得到如下响应:

I'm using OATH2, and when I request a token it works great and I get a response like this:

{
  "access_token": "227803d1-fe94-4e31-b496-3a03bafb9479",
  "token_type": "bearer",
  "refresh_token": "322f4ee9-4c48-4e06-a129-f4b6af93d664",
  "expires_in": 43199,
  "scope": "read write"
}

以某种方式,在此示例中它可以正常工作:

Somehow, it works correct in this example:

https://github.com/royclarkson/spring-rest-service-oauth

当我未经授权时,我想退回这样的东西:

And when I'm not authorized, I want back something like this:

{
  "error": "unauthorized",
  "error_description": "An Authentication object was not found in the SecurityContext"
}

但是我得到一个登录表格,我想要上面的回复.我究竟做错了什么?我完全无法理解为什么它在GitHub示例中起作用,而在我的情况下却无法理解.有没有一种方法可以完全禁用登录表单并强制json响应?

But I'm getting a login form, and I want the response above. What am I doing wrong? I litterally can't uderstand why it works in the GitHub example, and not in my case. Is there a way to completely disable the login form, and force the json response?

推荐答案

AuthenticationEntryPoint用于Spring安全性中的异常处理.

AuthenticationEntryPoint is used for exception handling in spring security.

如果已将oauth2添加到pom,则可以将OAuth2AuthenticationEntryPoint用作入口点,该入口点用于spring安全异常处理,如果您使用基本身份验证,则可以这样配置

If you have added the oauth2 to your pom, you can use OAuth2AuthenticationEntryPoint for you entry point, the Entry point is for spring security exception handling, if you are using the basic for your authentication, you can config like this

http
  .httpBasic().authenticationEntryPoint(getCustomerEntryPoint());

@Bean
protected AuthenticationEntryPoint getCustomerEntryPoint() {
    return new OAuth2AuthenticationEntryPoint();
}

您可以在OAuth2AuthenticationEntryPoint

// Try to extract a SpringSecurityException from the stacktrace
    Throwable[] causeChain = throwableAnalyzer.determineCauseChain(e);
    Exception ase = (OAuth2Exception) throwableAnalyzer.getFirstThrowableOfType(
            OAuth2Exception.class, causeChain);

    if (ase != null) {
        return handleOAuth2Exception((OAuth2Exception) ase);
    }

    ase = (AuthenticationException) throwableAnalyzer.getFirstThrowableOfType(AuthenticationException.class,
            causeChain);
    if (ase != null) {
        return handleOAuth2Exception(new UnauthorizedException(e.getMessage(), e));
    }

    ase = (AccessDeniedException) throwableAnalyzer
            .getFirstThrowableOfType(AccessDeniedException.class, causeChain);
    if (ase instanceof AccessDeniedException) {
        return handleOAuth2Exception(new ForbiddenException(ase.getMessage(), ase));
    }

    ase = (HttpRequestMethodNotSupportedException) throwableAnalyzer
            .getFirstThrowableOfType(HttpRequestMethodNotSupportedException.class, causeChain);
    if (ase instanceof HttpRequestMethodNotSupportedException) {
        return handleOAuth2Exception(new MethodNotAllowed(ase.getMessage(), ase));
    }

    return handleOAuth2Exception(new ServerErrorException(e.getMessage(), e));

它将尝试按顺序获取OAuth2ExceptionAuthenticationExceptionAccessDeniedException,我想您可以使用它.

it will try to get OAuth2Exception, AuthenticationException, AccessDeniedException in order, I think you can use this.

您还可以配置ExceptionTranslationFilter,此过滤器位于spring安全链中,它将捕获并处理其后的异常,例如AuthenticationExceptionAccessDeniedException,它是主要入口点,并且将对大多数身份验证方法(如FormLogin)很有帮助.

And you can also config the ExceptionTranslationFilter, this filter is in the spring security chain, and it will catch and handler the exception after it, like AuthenticationException, AccessDeniedException, and it is main entry point and will be helpful for most authentication method, like FormLogin.

http
  .exceptionHandling().authenticationEntryPoint(getCustomerEntryPoint());

如果您不使用spring oauth2,现在您已经了解了AuthenticationEntryPoint,因此您也可以实现自己的AuthenticationEntryPoint并自定义异常响应,只需重写commence方法即可,例如

If you are not use the spring oauth2, now you understand the AuthenticationEntryPoint, so you can also implement you own AuthenticationEntryPoint and custom your exception response, just overrider the commence method, like

BasicAuthenticationEntryPoint:它将返回"WWW-Authenticate"标头 LoginUrlAuthenticationEntryPoint:如果不进行身份验证,它将重定向到目标url

BasicAuthenticationEntryPoint: it will return 'WWW-Authenticate' header LoginUrlAuthenticationEntryPoint: it will redirect to target url when no authentcation

这篇关于在春季启动OAUTH2中返回RESTful/json响应而不是登录表单的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆