Spring Security Spring Boot 不接受我的前端请求

hs1ihplo  于 2022-12-29  发布在  Spring
关注(0)|答案(1)|浏览(143)

我想做一个简单的登录请求,我发送用户名和密码到后端,并试图获得一个访问令牌。当我测试从spring-boot请求工作得很好。
会有什么问题呢?
前端登录方式:

login(username: string, password: string) {
    return this.http.post(
        'http://localhost:8080/login',
        {
          username: username,
          password: password
        }
      )
      .pipe(
        catchError(this.handleError)
      );
  }

更新日期:

login(username: string, password: string) {
    const header = new HttpHeaders()
      .set('content-type', 'application/json')
    const params = new HttpParams()
      .set('print', 'pretty')
      .set('username', username)
      .set('password', password)
    return this.http.post(
        'http://localhost:8080/login',
        {},{
          headers : header,
          params: params,
        }
      )
      .pipe(
        catchError(this.handleError)
      );
  }

后端的登录方法:

@Slf4j
@CrossOrigin
public class CustomAuthorizationFilter extends OncePerRequestFilter {

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
        if (request.getServletPath().equals("/login") || request.getServletPath().equals("/token/refresh")) {
            filterChain.doFilter(request, response);
        } else {
            String authorizationHeader = request.getHeader(AUTHORIZATION);
            if (authorizationHeader != null && authorizationHeader.startsWith("Bearer ")) {
                try {
                    String token = authorizationHeader.substring("Bearer ".length());
                    Algorithm algorithm = Algorithm.HMAC256("secret".getBytes());
                    JWTVerifier verifier = JWT.require(algorithm).build();
                    DecodedJWT decodedJWT = verifier.verify(token);
                    String username = decodedJWT.getSubject();
                    String[] roles = decodedJWT.getClaim("roles").asArray(String.class);
                    Collection<SimpleGrantedAuthority> authorities = new ArrayList<>();
                    stream(roles).forEach(role-> {
                        authorities.add(new SimpleGrantedAuthority(role));
                    });
                    UsernamePasswordAuthenticationToken authenticationToken =
                            new UsernamePasswordAuthenticationToken(username, null, authorities);
                    SecurityContextHolder.getContext().setAuthentication(authenticationToken);
                    filterChain.doFilter(request, response);
                } catch (Exception e) {
                    log.error("Error# logging in: {}", e.getMessage());
                    response.setHeader("error", e.getMessage());
                    Map<String, String> error = new HashMap<>();
                    error.put("error_message", e.getMessage());
                    response.setContentType(APPLICATION_JSON_VALUE);
                    new ObjectMapper().writeValue(response.getOutputStream(), error);
                }
            } else {
                filterChain.doFilter(request, response);
            }
        }
    }
}

然后:(我的请求未到达此步骤)。

@Override
public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response) throws AuthenticationException {
    String username = request.getParameter("username");
    String password = request.getParameter("password");
    log.info("Username is: {}", username); log.info("Password is: {}", password);
    UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(username, password);
    return authenticationManager.authenticate(authenticationToken);
}
a0zr77ik

a0zr77ik1#

下面是您的错误:

public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response) throws AuthenticationException {
    String username = request.getParameter("username");

在后端代码的上述部分中,您希望用户名作为前端的查询参数。
在你的前端虽然你把它作为身体的一部分

this.http.post(
        'http://localhost:8080/login',
        {
          username: username,
          password: password
        }

统一后端和前端的查询参数,或者统一请求主体中的预期数据。

相关问题