在 Spring MVC rest api 中实现用户身份验证
Implementing user authentication in Spring MVC rest api
我已经构建了一个基本的 crud spring mvc rest api 并且想要添加基本身份验证以验证用户并添加登录和注销。我找到了涵盖 spring mvc.
的教程
我试过实现基本认证,代码如下:
@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
UserBuilder users = User.withDefaultPasswordEncoder();
auth.inMemoryAuthentication()
.withUser(users.username("marie").password("yourmarie").roles("USER"));
}
使用上面的代码,它提供了身份验证,但是当凭据无效时,它 returns 是一个例外。相反,如果可能的话,我希望返回某种 jason 或消息,以便我可以根据返回值在前端处理操作。
另一方面,如果我尝试在没有身份验证的情况下访问端点,它会给我一个登录表单。在这里,我也想回应一下。
此外,还想添加注销功能。
请指导。
提前致谢!
如果您发现异常,而凭据无效,则只需在您的控制器中捕获异常即可。并创建您自己的身份验证异常并用正确的消息抛出它。
catch (Exception ae) { throw new AuthenticationException("Invalid
credentials"); }
对于注销,您需要从存储(内存)中删除令牌如果
,您可以如下检查请求中的令牌
(StringUtils.hasText(httpServletRequest.getHeader("Authorization"))) {
String access_token = request.getHeader("Authorization"); }
我已经构建了一个基本的 crud spring mvc rest api 并且想要添加基本身份验证以验证用户并添加登录和注销。我找到了涵盖 spring mvc.
的教程我试过实现基本认证,代码如下:
@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
UserBuilder users = User.withDefaultPasswordEncoder();
auth.inMemoryAuthentication()
.withUser(users.username("marie").password("yourmarie").roles("USER"));
}
使用上面的代码,它提供了身份验证,但是当凭据无效时,它 returns 是一个例外。相反,如果可能的话,我希望返回某种 jason 或消息,以便我可以根据返回值在前端处理操作。
另一方面,如果我尝试在没有身份验证的情况下访问端点,它会给我一个登录表单。在这里,我也想回应一下。
此外,还想添加注销功能。
请指导。 提前致谢!
如果您发现异常,而凭据无效,则只需在您的控制器中捕获异常即可。并创建您自己的身份验证异常并用正确的消息抛出它。
catch (Exception ae) { throw new AuthenticationException("Invalid credentials"); }
对于注销,您需要从存储(内存)中删除令牌如果
,您可以如下检查请求中的令牌(StringUtils.hasText(httpServletRequest.getHeader("Authorization"))) { String access_token = request.getHeader("Authorization"); }