zoukankan      html  css  js  c++  java
  • 跨域问题解决

    1自定义filter 解决跨域

    response.setHeader("Access-Control-Allow-Origin", "*");
         response.setHeader("Access-Control-Allow-Credentials", "true");
           response.setHeader("Access-Control-Allow-Methods", "*");
         response.setHeader("Access-Control-Allow-Headers", "Content-Type,authorization,widthCredentials,x-merchant-role");
           response.setHeader("Access-Control-Expose-Headers", "*");
    

    2.spring security 配置解决跨域

    2.1 @CrossOrigin +配置http 请求 解决跨域

    package com.aila.config;
    
    import org.springframework.context.annotation.Bean;
    import org.springframework.context.annotation.Configuration;
    import org.springframework.core.annotation.Order;
    import org.springframework.security.authentication.AuthenticationManager;
    import org.springframework.security.config.annotation.web.builders.HttpSecurity;
    import org.springframework.security.config.annotation.web.builders.WebSecurity;
    import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
    import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
    import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
    import org.springframework.security.crypto.password.PasswordEncoder;
    
    @Configuration
    @EnableWebSecurity
    @Order(-1)
    class WebSecurityConfig extends WebSecurityConfigurerAdapter {
    
        /***
         * 忽略安全拦截的URL
         * @param web
         * @throws Exception
         */
        @Override
        public void configure(WebSecurity web) throws Exception {
            web.ignoring().antMatchers("/oauth/login",
                    "/oauth/logout","/oauth/toLogin","/login.html","/css/**","/data/**","/fonts/**","/img/**","/js/**");
        }
    
        /***
         * 创建授权管理认证对象
         * @return
         * @throws Exception
         */
        @Bean
        @Override
        public AuthenticationManager authenticationManagerBean() throws Exception {
            AuthenticationManager manager = super.authenticationManagerBean();
            return manager;
        }
    
        /***
         * 采用BCryptPasswordEncoder对密码进行编码
         * @return
         */
        @Bean
        public PasswordEncoder passwordEncoder() {
            return new BCryptPasswordEncoder();
        }
    
        /****
         *
         * @param http
         * @throws Exception
         */
        @Override
        public void configure(HttpSecurity http) throws Exception {
            http.csrf().disable()        //关闭跨域保护
                    .httpBasic()        //启用Http基本身份验证
                    .and()
                    .formLogin()       //启用表单身份验证
                    .and()
                    .authorizeRequests()    //限制基于Request请求访问
                    .anyRequest()
                    .authenticated();       //其他请求都需要经过验证
    
            //开启表单登录
            http.formLogin().loginPage("/oauth/toLogin")//设置访问登录页面的路径
                    .loginProcessingUrl("/oauth/login");//设置执行登录操作的路径
        }
    }
    package com.aila.Controller;
    
    import com.aila.Service.AuthService;
    import com.aila.utils.AuthToken;
    import com.aila.utils.CookieUtil;
    import com.aila.utils.Result;
    import com.aila.utils.StatusCode;
    import org.apache.commons.lang.StringUtils;
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.beans.factory.annotation.Value;
    import org.springframework.stereotype.Controller;
    import org.springframework.web.bind.annotation.CrossOrigin;
    import org.springframework.web.bind.annotation.RequestMapping;
    import org.springframework.web.bind.annotation.ResponseBody;
    
    import javax.servlet.http.HttpServletResponse;
    
    /**
     * @Author: {---chenzhichao---}
     * @Date: 2020/6/5 11:20
     */
    @RequestMapping("/oauth")
    @Controller
    @CrossOrigin
    public class Oath2Controller {
        @Value("${auth.clientId}")
        private String clientId;
    
        @Value("${auth.clientSecret}")
        private String clientSecret;
    
        @Value("${auth.cookieDomain}")
        private String cookieDomain;
    
        @Value("${auth.cookieMaxAge}")
        private int cookieMaxAge;
    
        @Autowired
        private AuthService authService;
    
        @RequestMapping("/login")
        @ResponseBody
        public Result login(String username, String password, HttpServletResponse response){
            //校验参数
            if (StringUtils.isEmpty(username)){
                throw new RuntimeException("请输入用户名");
            }
            if (StringUtils.isEmpty(password)){
                throw new RuntimeException("请输入密码");
            }
            //申请令牌 authtoken
            AuthToken authToken = authService.login(username, password, clientId, clientSecret);
    
            //将jti的值存入cookie中
            /*this.saveJtiToCookie(authToken.getJti(),response);*/
    
            //返回结果
    
            //String UserAccessToken = authToken.getAccessToken();
    
            //System.out.println(UserAccessToken);
            return new Result(true, StatusCode.OK,"登录成功",authToken.getJti());
        }
    
        private void saveJtiToCookie(String jti, HttpServletResponse response) {
            CookieUtil.addCookie(response,cookieDomain,"/","uid",jti,cookieMaxAge,false);
        }
    
    }
    

      2.2自定义crosconfig解决跨域问题   本人没有试验过 而且颗粒大  配置之后 所有请求都将支持跨域(虽然现在都是前后端分离 但是从设计角度来说不说很好)

    package com.chinagoods.barge.config.security;

    import org.springframework.context.annotation.Bean;
    import org.springframework.context.annotation.Configuration;
    import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
    import org.springframework.security.config.annotation.web.builders.HttpSecurity;
    import org.springframework.security.config.annotation.web.builders.WebSecurity;
    import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
    import org.springframework.web.cors.CorsConfiguration;
    import org.springframework.web.cors.CorsConfigurationSource;
    import org.springframework.web.cors.UrlBasedCorsConfigurationSource;

    /**
    * 配置controller 上的注解开启
    * 配置spring security 认证放行全部路径
    * @Author: {---chenzhichao---}
    * @Date: 2020/6/16 18:09
    */
    @Configuration
    @EnableGlobalMethodSecurity(prePostEnabled = true, securedEnabled = true)
    public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
    /**
    * 配置静态文件忽略路径
    * @param web spring security web对象
    * @throws Exception 异常
    */
    @Override
    public void configure(WebSecurity web) throws Exception {
    web.ignoring()
    .antMatchers("/**");
    }

    /**
    * 配置http请求 忽略全部路径安全认证
    * @param http spring security http对象
    * @throws Exception 异常
    */
    @Override
    public void configure(HttpSecurity http) throws Exception {
    http.authorizeRequests()
    .antMatchers("/**").permitAll();
    }

    /**
    * 配置跨域
    * @return
    */
    @Bean
    CorsConfigurationSource corsConfigurationSource() {
    CorsConfiguration configuration = new CorsConfiguration();
    configuration.addAllowedOrigin("*");
    configuration.addAllowedMethod("*");
    configuration.addAllowedHeader("*");
    configuration.setAllowCredentials(true);
    UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
    source.registerCorsConfiguration("/**", configuration);
    return source;
    }
    }

    推荐使用2.1

     

  • 相关阅读:
    Atitit.获得向上向下左的右的邻居的方法 软键盘的设计..
    Atitit.css 规范 bem 项目中 CSS 的组织和管理
    Atitit.css 规范 bem  项目中 CSS 的组织和管理
    Atitit.android js 的键盘按键检测Back键Home键和Menu键事件
    Atitit.android js 的键盘按键检测Back键Home键和Menu键事件
    Atitit.java相比c#.net的优点 优缺点  v2 q330
    Atitit.java相比c#.net的优点 优缺点  v2 q330
    Atitit.android  jsbridge v1新特性
    Atitit.android  jsbridge v1新特性
    Atitit. Toast alert loading js控件   atiToast v2新特性
  • 原文地址:https://www.cnblogs.com/kyousuke/p/13201271.html
Copyright © 2011-2022 走看看