【问题标题】:How to secure my front Angular application with an OAuth and a BAck java?如何使用 OAuth 和 BAck java 保护我的前端 Angular 应用程序?
【发布时间】:2022-09-27 09:22:08
【问题描述】:

我有一个 Java11 spring boot Angular 13 应用程序,并且我有 open id connect 身份验证。

因此,在前面,我有令牌并将其添加到我的请求中,在后面我有应用程序的安全性,但我在 TRACE 级别时没有日志,但我没有没有登录前台电话。

所以不知道是什么阻碍了前端和java后端的通信。

通信 back-OAuth ok,front-OAuth ok

OAuth2 模式是

请求前面的隐式授权。

Request URL: http://localhost:8080/api/domains/sync
Referrer Policy: strict-origin-when-cross-origin
Provisional headers are shown
Learn more
Accept: application/json, text/plain, */*
Authorization: Bearer [object Object]
Content-Type: application/json
Referer: http://localhost:4200/
sec-ch-ua: \"Google Chrome\";v=\"105\", \"Not)A;Brand\";v=\"8\", \"Chromium\";v=\"105\"
sec-ch-ua-mobile: ?0
sec-ch-ua-platform: \"Windows\"
User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/105.0.0.0 Safari/537.36


Request URL: http://localhost:8080/api/domains/sync
Referrer Policy: strict-origin-when-cross-origin
Accept: */*
Accept-Encoding: gzip, deflate, br
Accept-Language: fr-FR,fr;q=0.9
Access-Control-Request-Headers: authorization,content-type
Access-Control-Request-Method: POST
Connection: keep-alive
Host: localhost:8080
Origin: XXX
Referer: http://localhost:4200/
Sec-Fetch-Dest: empty
Sec-Fetch-Mode: cors
Sec-Fetch-Site: same-site
User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/105.0.0.0 Safari/537.36

@Injectable({
  providedIn: \'root\',
})
export class TokenInterceptorService implements HttpInterceptor {
  constructor(private authService: InitialAuthService) {}
  intercept(
    request: HttpRequest<any>,
    next: HttpHandler
  ): Observable<HttpEvent<any>> {
    const  token = this.authService.decodedAccessToken? this.authService.decodedAccessToken:null;
    if (typeof token != \'undefined\' && token) {
      request = request.clone({
        setHeaders: {
          Authorization: `Bearer ` + token,
        },
      });
      console.debug(\"new request =>\");
      console.debug(request);
    }
    return next.handle(request).pipe(
      catchError((err) => {
        console.error(err);
        if (err.status === 401) {
        }
        const error = err.error.message || err.statusText;
        return throwError(error);
      })
    );
  }
}

爪哇

@Configuration
public class OAuth2SecurityConfig {
    @Bean
    SecurityWebFilterChain springSecurityFilterChain(ServerHttpSecurity http) {
        http
                .authorizeExchange(exchanges ->
                        exchanges
                                .pathMatchers(\"/\", \"/error\").permitAll()
                                .anyExchange().authenticated()
                )
                .oauth2Login((Customizer<ServerHttpSecurity.OAuth2LoginSpec>) withDefaults());
        return http.build();
    }
}
@Controller
public class UserController {
    @GetMapping(\"/\")
    public String index() {
        return \"index\";
    }

    @GetMapping(\"/user\")
    public String user(Model model,
                       @AuthenticationPrincipal OidcUser oidcUser) {
        model.addAttribute(\"userName\", oidcUser.getName());
        model.addAttribute(\"audience\", oidcUser.getAudience());
        return \"user\";
    }
}

pom.xml

<dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-oauth2-client</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-security</artifactId>
        </dependency>

    标签: java angular oauth


    【解决方案1】:

    首先,不要尝试解码或解释访问令牌客户端(在您的 Angular 应用程序中)。只需在授权标头中转发它。如果您需要客户端上经过身份验证的用户数据,请使用 ID-token(或查询授权服务器用户端点)

    其次,不要在 Angular 应用程序中自己编写 OAuth2 逻辑。请改用 angular-auth-oidc-client 之类的库。它提供了拦截器(就像你写的那样)、路由保护、访问令牌刷新(在过期之前)等等。

    最后,您应该紧急阅读this article。在 OAuth2 中,Spring API 是“资源服务器”,而不是“客户端”。配置如下(详见文章):

    • 使用spring-boot-starter-oauth2-resource-server 而不是spring-boot-starter-oauth2-client
    • 使用http.oauth2ResourceServer().jwt()(如果访问令牌不是JWT,则使用http.oauth2ResourceServer().opaqueToken())而不是http.oauth2Login(...)

    【讨论】:

      猜你喜欢
      • 2018-11-04
      • 2012-03-29
      • 2021-06-25
      • 1970-01-01
      • 2023-03-15
      • 2020-10-15
      • 2013-07-13
      • 2020-07-05
      • 1970-01-01
      相关资源
      最近更新 更多