当前位置: 首页 > 知识库问答 >
问题:

嗨!Spring安全角度认证有问题

慕容越泽
2023-03-14

就像在本主题中一样,我的Spring Security应用程序也有问题。单击“身份验证”按钮时,即使输入了正确的数据,也会在控制台中看到:

访问位于“”的XMLHttpRequesthttp://localhost:8080/api/v1/basicauth“起源”http://localhost:4200'已被CORS策略阻止:对飞行前请求的响应未通过访问控制检查:它没有HTTP ok状态。

而且

收到http://localhost:8080/api/v1/basicauthnet::ERR_失败

这是我在angular中的代码:

auth。服务ts

import { HttpClient } from '@angular/common/http';
import { Injectable } from '@angular/core';
import { map } from 'rxjs/operators';

@Injectable({
  providedIn: 'root'
})
export class AuthenticationService {

  // BASE_PATH: 'http://localhost:8080'
  USER_NAME_SESSION_ATTRIBUTE_NAME = 'authenticatedUser'

  public username: String;
  public password: String;

  constructor(private http: HttpClient) {

  }

  authenticationService(username: String, password: String) {
    return this.http.get(`http://localhost:8080/api/v1/basicauth`,
      { headers: { authorization: this.createBasicAuthToken(username, password) } }).pipe(map((res) => {
        this.username = username;
        this.password = password;
        this.registerSuccessfulLogin(username, password);
      }));
  }

  createBasicAuthToken(username: String, password: String) {
    return 'Basic ' + window.btoa(username + ":" + password)
  }

  registerSuccessfulLogin(username, password) {
    sessionStorage.setItem(this.USER_NAME_SESSION_ATTRIBUTE_NAME, username)
  }

  logout() {
    sessionStorage.removeItem(this.USER_NAME_SESSION_ATTRIBUTE_NAME);
    this.username = null;
    this.password = null;
  }

  isUserLoggedIn() {
    let user = sessionStorage.getItem(this.USER_NAME_SESSION_ATTRIBUTE_NAME)
    if (user === null) return false
    return true
  }

  getLoggedInUserName() {
    let user = sessionStorage.getItem(this.USER_NAME_SESSION_ATTRIBUTE_NAME)
    if (user === null) return ''
    return user
  }
}

登录。组成部分ts

import { Component, OnInit } from '@angular/core';
import { Router, ActivatedRoute } from '@angular/router';
import { AuthenticationService } from './auth.service';

@Component({
  selector: 'app-login',
  templateUrl: './login.component.html',
  styleUrls: ['./login.component.css']
})
export class LoginComponent implements OnInit {

  username: string;
  password : string;
  errorMessage = 'Invalid Credentials';
  successMessage: string;
  invalidLogin = false;
  loginSuccess = false;

  constructor(
    private route: ActivatedRoute,
    private router: Router,
    private authenticationService: AuthenticationService) {   }

  ngOnInit() {
  }

  handleLogin() {
    this.authenticationService.authenticationService(this.username, this.password).subscribe((result)=> {
      this.invalidLogin = false;
      this.loginSuccess = true;
      this.successMessage = 'Login Successful.';
      this.router.navigate(['/products']);
    }, () => {
      console.log(this.username);
      console.log(this.password);
      this.invalidLogin = true;
      this.loginSuccess = false;
    });      
  }
}

http.service.ts

import { HttpInterceptor, HttpRequest, HttpHandler, HttpEvent, HttpHeaders } from '@angular/common/http';
import { Injectable } from '@angular/core';
import { Observable } from 'rxjs';
import { AuthenticationService } from './login/auth.service';

@Injectable()
export class HttpInterceptorService implements HttpInterceptor {

    constructor(private authenticationService: AuthenticationService) { }

    intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
        if (this.authenticationService.isUserLoggedIn() && req.url.indexOf('basicauth') === -1) {
            const authReq = req.clone({
                headers: new HttpHeaders({
                    'Content-Type': 'application/json',
                    'Authorization': `Basic ${window.btoa(this.authenticationService.username + ":" + this.authenticationService.password)}`
                })
            });
            return next.handle(authReq);
        } else {
            return next.handle(req);
        }
    }
}

登录。组成部分html

<div class="container col-lg-6">
  <h1 class="text-center">Login</h1>
  <div class="card">
    <div class="card-body">
      <form class="form-group">
        <div class="alert alert-warning" *ngIf='invalidLogin'>{{errorMessage}}</div>
        <div class="alert alert-success" *ngIf='loginSuccess'>{{successMessage}}</div>
        <div class="form-group">
          <label for="email">User Name :</label>
          <input type="text" class="form-control" id="username" [(ngModel)]="username" placeholder="Enter User Name"
            name="username">
        </div>
        <div class="form-group">
          <label for="pwd">Password:</label>
          <input type="password" class="form-control" [(ngModel)]="password" id="password" placeholder="Enter password"
            name="password">
        </div>
        <button (click)=handleLogin() class="btn btn-success">Login</button>
      </form>
    </div>
  </div>
</div>

我的java代码:

package com.shop.shop.security;

import org.springframework.http.HttpMethod;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;

public class SpringSecurityConfig extends WebSecurityConfigurerAdapter {

    @Override
    protected void configure(HttpSecurity httpSecurity) throws Exception{
        httpSecurity.csrf().disable()
                .authorizeRequests()
                .antMatchers(HttpMethod.OPTIONS, "/**")
                .permitAll()
                .anyRequest()
                .authenticated()
                .and()
                .httpBasic();
    }

}
package com.shop.shop.security;

import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@CrossOrigin(origins = "http://localhost:4200")
@RestController
@RequestMapping("api/v1")
public class BasicAuthController {

    @GetMapping(path = "/basicauth")
    public AuthenticationBean basicauth(){
        return new AuthenticationBean("You are authenticated!");
    }

}
package com.shop.shop.security;

public class AuthenticationBean {

    private String message;

    public AuthenticationBean(String message) {
        this.message = message;
    }

    public String getMessage() {
        return message;
    }

    public void setMessage(String message) {
        this.message = message;
    }

    @Override
    public String toString() {
        return String.format("HelloWorldBean [message=%s]", message);
    }
}

你能帮我解决和理解那种问题吗?谢谢!:)

共有1个答案

易镜
2023-03-14

问题在于CORS,您应该添加如下内容:

public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain chain)
        throws IOException, ServletException {

    HttpServletRequest request = (HttpServletRequest) servletRequest;
    System.out.println("CORSFilter HTTP Request: " + request.getMethod());

    // Authorize (allow) all domains to consume the content
    ((HttpServletResponse) servletResponse).addHeader("Access-Control-Allow-Origin", "*");
    ((HttpServletResponse) servletResponse).addHeader("Access-Control-Allow-Methods","GET, OPTIONS, HEAD, PUT, POST");

    HttpServletResponse resp = (HttpServletResponse) servletResponse;

    // For HTTP OPTIONS verb/method reply with ACCEPTED status code -- per CORS handshake
    if (request.getMethod().equals("OPTIONS")) {
        resp.setStatus(HttpServletResponse.SC_ACCEPTED);
        return;
    }

    // pass the request along the filter chain
    chain.doFilter(request, servletResponse);
}
 类似资料:
  • gRPC 被设计成可以利用插件的形式支持多种授权机制。本文档对多种支持的授权机制提供了一个概览,并且用例子来论述对应API,最后就其扩展性作了讨论。 马上将会推出更多文档和例子。 支持的授权机制 SSL/TLS gRP 集成 SSL/TLS 并对服务端授权所使用的 SSL/TLS 进行了改良,对客户端和服务端交换的所有数据进行了加密。对客户端来讲提供了可选的机制提供凭证来获得共同的授权。 OAut

  • 我正在研究云应用程序的身份验证服务部分,我创建了以下安全配置类。 我不太清楚configure(HttpSecurity http)方法的链方法。身份验证服务将只接收“登录”和“注册”请求。 由于未授权任何内容,是否应删除authorizeRequests()方法? 我不确定anyRequest().Authenticated()部分是否真的需要?

  • Cookies 和 secure cookies 你可以使用 set_cookie 方法在用户的浏览器中设置 cookies: class MainHandler(tornado.web.RequestHandler): def get(self): if not self.get_cookie("mycookie"): self.set_cooki

  • 包括平台认证体系架构和安全告警等内容。 认证体系 认证体系主要包括认证源、域、项目、组、用户、权限、角色等信息。 安全告警 安全告警即实时监测系统中的安全告警事件,如异常登录等,当发现安全问题后,将会及时通知管理员用户进行处理等。

  • 介绍安全检查、安全告警、操作日志的内容。 安全检查 平台会根据系统内置规则扫描下图中的安全性较低的资源,用户可以按照费用优化处理资源,提升平台资源的安全性。详情请参考认证与安全-安全检查。 安全告警 安全告警即实时监测系统中的安全告警事件,如异常登录等,当发现安全问题后,将会及时通知管理员用户进行处理等。目前仅支持异常登录的安全告警事件,当用户连续登录失败后被锁定将会发送安全告警记录发送给锁定用户

  • 我需要匿名公开执行器“health”endpoint,这意味着对该endpoint的请求不会通过SiteMinder,因此,HTTP请求头中不会出现SM_USER头。 我面临的问题是,无论我如何尝试配置“health”endpoint,框架都会抛出,因为当请求没有通过SiteMinder时,预期的头(“sm_user”)不存在。 这是我最初的安全配置: 我试过的事情: 为匿名访问而不是Permit