spring security oauth 开启formLogin请求401的时候返回页面而不是json怎么处理

新手上路,请多包涵

RT,因为需要为/oauth/authorize开启formLogin,但是在开启之后发现访问接口在未授权时会返回请求码200,并且返回登陆页面,但是这很明显不是我们想要的,请问应该如何处理?

阅读 6.7k
2 个回答

spring security 未登录登录状态访问无权限资源都会出现访问异常,这个异常由 ExceptionTranslationFilter 处理,其中:

  • 未登录,异常由 AuthenticationEntryPoint 处理,其中重定向至Login页面操作也是个EntryPoint:LoginUrlAuthenticationEntryPoint,他专为formLogin做跳转

image.png

你可以自定义实现AuthenticationEntryPoint覆盖他

@Component
@Configuration
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        // 未登录响应
        http.exceptionHandling().authenticationEntryPoint(new NoLoginEntryPoint());
    }
}
  • 已登录,异常由 AccessDeniedHandler 处理,同样可以自定义实现并配置
@Component
@Configuration
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        // 无权限响应
        http.exceptionHandling().accessDeniedHandler(new NoPrivilegeHandler());
    }
}

其实我依然有一点不太明白,api/**这些的返回值是由mvc决定的。仅仅说认证和授权,如果你是想说失败后返回json而不是跳转。如果是认证失败 ,比如密码错误等,就配置login.failureHandler()。如果是权限不够(.accessDeniedHandler)或者未认证(.authenticationEntryPoint),就配置exceptionHandling()。由自己接管定义如何返回,即楼上所说,楼上有图,我就不截了。

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题