首页 > 其他分享 >八、匿名访问和跨域

八、匿名访问和跨域

时间:2023-06-09 21:01:24浏览次数:191  
标签:return 跨域 访问 匿名 anonymous pathMatchers http anoy

一、匿名访问

新建AnonymousController

  @RestController
  @RequestMapping("/anoy")
  public class AnonymousController {

      @RequestMapping("/hello")
      public Mono<String> hello() {
          return Mono.just("123");
      }
  }

如果想要访问路径匹配/anoy/**这种模式的请求不需要登录即可访问。要怎么做呢?在Spring Reactive Security中可以使用匿名访问。

 @Bean
public SecurityWebFilterChain springSecurityFilterChain(ServerHttpSecurity http) {
    http
            .authorizeExchange(exchanges -> exchanges
                    .pathMatchers(LOGIN_PAGE).permitAll()
                    .pathMatchers("/verify_code").permitAll()
                    .pathMatchers("/anoy/**").hasRole("ANONYMOUS")
                    .anyExchange().authenticated()
            )
            .formLogin()
            .loginPage(LOGIN_PAGE)
            .and()
            .csrf().disable()
            .anonymous()
            .and()
            .logout()
            ;

    http.addFilterAt(authenticationManager(), SecurityWebFiltersOrder.FORM_LOGIN);
    return http.build();
}

在SecurityWebFilterChain中加入anonymous配置并添加pathMatchers("/anoy/**").hasRole("ANONYMOUS")权限控制。重启后不需要登录即可访问/anoy/hello。但是访问其他资源还是需要登录。

 

SecurityWebFilterChain中的anonymous()是配置AnonymousAuthenticationWebFilter的。可以看下anonymous()默认实现:

	public AnonymousSpec anonymous() {
	    if (this.anonymous == null) {
			this.anonymous = new AnonymousSpec();
		}
		return this.anonymous;
	}

AnonymousAuthenticationWebFilter是由AnonymousSpec配置的,看下属性:

	private String key;

	private AnonymousAuthenticationWebFilter authenticationFilter;

	private Object principal = "anonymousUser";

	private List<GrantedAuthority> authorities = AuthorityUtils.createAuthorityList("ROLE_ANONYMOUS");

可以看到匿名用户角色是ROLE_ANONYMOUS

AnonymousAuthenticationWebFilter

@Override
public Mono<Void> filter(ServerWebExchange exchange, WebFilterChain chain) {
	return ReactiveSecurityContextHolder.getContext().switchIfEmpty(Mono.defer(() -> {
		Authentication authentication = createAuthentication(exchange);
		SecurityContext securityContext = new SecurityContextImpl(authentication);
		logger.debug(LogMessage.format("Populated SecurityContext with anonymous token: '%s'", authentication));
		return chain.filter(exchange)
				.subscriberContext(ReactiveSecurityContextHolder.withSecurityContext(Mono.just(securityContext)))
				.then(Mono.empty());
	})).flatMap((securityContext) -> {
		logger.debug(LogMessage.format("SecurityContext contains anonymous token: '%s'",
				securityContext.getAuthentication()));
		return chain.filter(exchange);
	});
}

	protected Authentication createAuthentication(ServerWebExchange exchange) {
	      return new AnonymousAuthenticationToken(this.key, this.principal, this.authorities);
  	}

创建了AnonymousAuthenticationToken。

二、跨域

跨域只存现在前后端分离的项目中。当前端的部署ip或端口与后端的ip或端口不同时就会出现跨域。解决方案就是添加允许跨域的四个响应头。分别是Access-Control-Allow-Origin,Access-Control-Allow-Headers,Access-Control-Allow-Credentials,Access-Control-Allow-Method。一般不会直接设置响应头。而是通过CORS(跨域资源共享)来设置的。

 

单独新建html文件模拟前后端分离:

<!DOCTYPE html>
<html lang="">
  <head>
    <meta charset="utf-8">
    <title></title>
    
    <script src="https://cdn.bootcdn.net/ajax/libs/jquery/3.6.4/jquery.js"></script>
    
  </head>
  <body>
    <div id="content"></div>
    
    <button onclick="getData()">点击</button>
  </body>
  
  <script>
     function getData() {
        $.get('http://localhost:8080/anoy/hello',{}, function(res) {
                $('#content').html(res)
            })
     }
  </script>
</html>

在浏览器打开后点击按钮,查看浏览器控制台:
 

 

修改SecurityWebFilterChain:

@Bean
public SecurityWebFilterChain springSecurityFilterChain(ServerHttpSecurity http) {
    http
            .authorizeExchange(exchanges -> exchanges
                    .pathMatchers(LOGIN_PAGE).permitAll()
                    .pathMatchers("/verify_code").permitAll()
                    .pathMatchers("/anoy/**").hasRole("ANONYMOUS")
                    .anyExchange().authenticated()
            )
            .formLogin()
            .loginPage(LOGIN_PAGE)
            .and()
            .csrf().disable()
            .anonymous()
            .and()
            .cors()
            .configurationSource((exchange) -> {
                CorsConfiguration corsConfiguration = new CorsConfiguration();
                corsConfiguration.addAllowedOrigin("*");
                corsConfiguration.addAllowedMethod(HttpMethod.POST);
               
                return corsConfiguration;
            })
            .and()
            .logout()

            ;

    http.addFilterAt(authenticationManager(), SecurityWebFiltersOrder.FORM_LOGIN);
    return http.build();
}

增加了cors,addAllowedOrigin("*")表示所有的ip都可以访问,addAllowedMethod(HttpMethod.POST)表示添加了POST方法访问。默认允许GETHEAD方法。因为登录接口是POST方式,必须要添加POST的CorsConfiguration。重启后点击页面按钮:

 

标签:return,跨域,访问,匿名,anonymous,pathMatchers,http,anoy
From: https://www.cnblogs.com/shigongp/p/17470155.html

相关文章

  • 帮您了解CDN节点如何做到访问加速与安全防护
    本文分享自天翼云开发者社区《帮您了解CDN节点如何做到访问加速与安全防护》,作者:尹****荷 网站业务痛点在当前网站快速发展的背景下,网站业务突增往往伴随着一系列网络安全隐患。主要会有以下痛点:1.高并发压力大:网站在业务突增中,会带来高并发的问题,可能会导致服务器资源耗尽......
  • EasyRTMPLive拉转推硬件设备访问端口返回404报错,该如何解决?
    TSINGSEE青犀视频的各个平台部署灵活,视频能力丰富且全面、能满足用户的多场景视频监控需求。平台各具特点,可支持多类型的设备、多协议接入,包括国标GB28181协议、RTMP/RTSP/Onvif协议、海康EHOME、海康SDK、大华SDK等,在视频流分发上,能支持全终端、全平台的视频流输出,包括RTSP、RTMP......
  • 利用云服务器实现内网穿透(frp),开启个人电脑(windows)可远程桌面访问
     前言:利用微软自带的远程桌面进行访问,但无奈没有固定的公网地址,使用其他三方软件免费使用会有网络延迟等问题,因此需要一个相对稳妥的方式,那便是配合frp内网穿透实现远程访问个人电脑前提:有一台云服务器(需要公网ip,最好是国内的,延迟会较低) 教程步骤:1.下载frpfrp分为客......
  • Vue 调试访问本地后端接口配置
    记录一下本地测试前端的时候怎么访问本地后端接口。时间太长容易忘。。。。1、首先要知道前端在访问后端的时候是怎么加上后端接口地址的。如下图,找到封装http请求的文件,src/utils/rerquest.js该图中的baseURL就是访问时我们加上的后端请求地址。baseURL:process.env.VUE_APP......
  • chrome 跨域问题解决
    1.后端设置了跨域,https下可以,http不可以高版本chrome配置了策略,如果访问私有网络,会出现禁止跨域chrome://flags/#block-insecure-private-network-requestsBlockinsecureprivatenetworkrequests.......
  • ruby 访问 ceph
    #!/usr/bin/envruby#通过restfulAPIrequire"base64"require"openssl"require"net/http"PublicKey="publicKey"PrivateKey="privateKey"defgen_auth(http_method,bucket,filename,gmttime)sign=......
  • MATLAB匿名函数解析
    在MATLAB中,匿名函数也被称为内联函数。它是一种无需用户定义的短小的函数表达式,通常用于一次性的简单计算。创建一个匿名函数可以使用以下语法:function_handle=@(input_arguments)expression这里的function_handle是一个指向函数的句柄,input_arguments是一个输入参数列表,而......
  • java 访问ingress https报错javax.net.ssl.SSLHandshakeException: Received fatal al
    一、报错及部署环境Java程序访问测试域名https方法正常,访问生产域名https域名报错,报错如下javax.net.ssl.SSLHandshakeException:Receivedfatalalert:protocol_version测试环境使用KubeSphereingress生产环境使用阿里云ACK服务的ingress配置二、问题原因客户端......
  • 【前端跨域】CORS跨域问题解决思路
    目录一、Nginx跨域配置二、Spring项目跨域配置参考资料一、Nginx跨域配置在Nginx中配置跨域请求,主要可以通过设置HTTP响应头部的方式进行。以下是具体实现步骤:在Nginx的配置文件中找到对应location配置块,例如:server{listen80;server_nameexample.com;......
  • GitHub无法访问的解决方案
    1.情景展示 2.具体分析GitHub网站无法访问或者网页加载慢,都是网络问题造成的。我们访问某个网站,其实,是操作系统通过域名解析器(DNS解析器)解析域名拿到对应的IP地址,然后再去访问。 3.解决方案方案一:修改hosts文件hosts文件的作用是:配置在这里的域名,将不会走域名解析器,......