【问题标题】:Implementing user authentication in Spring MVC rest api在 Spring MVC rest api 中实现用户认证
【发布时间】:2019-05-19 12:29:57
【问题描述】:

我已经构建了一个基本的 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"));
}

使用上面的代码,它提供了身份验证,但是当凭据无效时,它会返回异常。相反,如果可能的话,我希望返回某种 jason 或消息,以便我可以根据返回的值在前端处理操作。

另一方面,如果我尝试在没有身份验证的情况下访问端点,它会给我一个登录表单。在这里,我也想要一个回应。

另外,还想添加注销功能。

请指导。 提前致谢!

【问题讨论】:

  • 如果您发现异常,而凭据无效,则只需在控制器中捕获异常。并创建您自己的身份验证异常并使用正确的消息将其抛出。 catch (Exception ae) { throw new AuthenticationException("Invalid credentials");对于注销,您需要从存储(内存)中删除令牌您可以在请求中检查令牌,如下所示 if (StringUtils.hasText(httpServletRequest.getHeader("Authorization"))) { String access_token = request.getHeader("Authorization" ); }
  • @ColinShah 感谢您的指导。但是,现在我收到 cors 错误:预检请求不允许重定向。我已经为 api 方法添加了 @CrossOrigin(origins = "localhost:8585"),因为我是从 localhost:8585 调用它。不过,我得到了错误。
  • 尝试在SecurityConfig中配置http.cors..spring.io/blog/2015/06/08/cors-support-in-spring-framework
  • 我添加了@Override protected void configure(HttpSecurity http) throws Exception { http.cors(); } 在我的安全配置中并且错误消失了,但是即使我发送了不正确的用户名或密码,我也会得到结果。

标签: java spring spring-security restful-authentication spring-rest


【解决方案1】:

如果您发现异常,而凭据无效,则只需在控制器中捕获异常即可。并创建您自己的身份验证异常并使用正确的消息将其抛出。

catch (Exception ae) { throw new AuthenticationException("Invalid 凭据"); }

对于注销,您需要从存储(内存)中删除令牌您可以在请求中检查令牌,如下所示

(StringUtils.hasText(httpServletRequest.getHeader("Authorization"))) { String access_token = request.getHeader("授权"); }

https://www.baeldung.com/java-config-spring-security

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-05-03
    • 1970-01-01
    • 2011-11-03
    • 2013-07-22
    • 2017-09-14
    • 2015-07-07
    • 1970-01-01
    相关资源
    最近更新 更多