Spring Security Oauth2 验证失败返回自定义异常信息(/oauth/token登录)

自定义异常继承OAuth2Exception

public class AuthException extends OAuth2Exception {
    private String code;

    public AuthException (String code, String msg) {
        super(msg);
        this.code=code;
    }

    @Override
    public int getHttpErrorCode() {
        return 200;
    }

    @Override
    public String getOAuth2ErrorCode() {
        return code;
    }
}

说明:

getHttpErrorCode()方法返回状态需在org.springframework.http.HttpStatus中存在

使用:

throw new AuthException("ssCode","登录错了");

返回:

{
  "error" : "ssCode",
  "error_description" : "登录错了"
}

要关闭Spring Security OAuth2的默认登录表单并自定义登录页面,您需要执行以下操作: 1. 创建一个自定义登录页面,例如/login。 2. 在Spring Security配置中禁用默认登录表单,如下所示: ``` @Override protected void configure(HttpSecurity http) throws Exception { http .authorizeRequests() .antMatchers("/login").permitAll() .anyRequest().authenticated() .and() .formLogin() .loginPage("/login") .permitAll() .and() .logout() .permitAll(); } ``` 在上面的代码中,`.antMatchers("/login").permitAll()`表示允许所有用户访问/login页面,并且`.formLogin().loginPage("/login").permitAll()`指定了自定义登录页面的URL。 3. 创建一个自定义登录表单,该表单将POST请求发送到Spring Security的/oauth/token端点,以便验证用户凭据。以下是示例HTML代码: ``` <form method="post" action="/oauth/token"> <div> <label for="username">Username:</label> <input type="text" id="username" name="username"/> </div> <div> <label for="password">Password:</label> <input type="password" id="password" name="password"/> </div> <div> <input type="submit" value="Login"/> </div> <input type="hidden" name="grant_type" value="password"/> <input type="hidden" name="scope" value="read write"/> <input type="hidden" name="client_id" value="my-client"/> <input type="hidden" name="client_secret" value="my-secret"/> </form> ``` 在上面的代码中,`<input type="hidden" name="grant_type" value="password"/>`表示使用密码授权类型进行身份验证,`<input type="hidden" name="scope" value="read write"/>`指定访问令牌的作用域,`<input type="hidden" name="client_id" value="my-client"/>`和`<input type="hidden" name="client_secret" value="my-secret"/>`指定客户端ID和密钥。 4. 使用您选择的Web框架创建/login端点,并在该端点上呈现自定义登录表单。当用户提交表单时,将使用Spring Security OAuth2的/oauth/token端点验证用户凭据并返回访问令牌。 请注意,此方案仅适用于密码授权类型。如果您需要其他授权类型(例如授权代码或隐式授权),则需要实现相应的授权流程。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值