加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 综合聚焦 > 服务器 > 安全 > 正文

具有跨源资源共享(CORS)的AngularJS spring安全登录/注销

发布时间:2020-12-17 18:08:55 所属栏目:安全 来源:网络整理
导读:问题陈述:我的UI应用程序在9000端口(grunt项目)上运行,我的服务器端 spring引导项目在8421端口上运行.除登录和注销外,我能够从我的UI应用程序中点击所有URL.请告诉我如何使用CORS配置spring security登录和注销. App.js $scope.login = function() { $http.
问题陈述:我的UI应用程序在9000端口(grunt项目)上运行,我的服务器端 spring引导项目在8421端口上运行.除登录和注销外,我能够从我的UI应用程序中点击所有URL.请告诉我如何使用CORS配置spring security登录和注销.

App.js

$scope.login = function() {
        $http.post('http://localhost:8421/login',$.param($scope.credentials),{
          headers : {
            'content-type' : 'application/x-www-form-urlencoded'
          }
        }).success(function() {
          console.log('login success');
          });
        }).error(function() {
          console.log('login error');
        });
      };

SecurityConfiguration.java

public class SecurityConfiguration extends WebSecurityConfigurerAdapter {

@Override
    protected void configure(HttpSecurity http) throws Exception {

        http.addFilterBefore(new SimpleCORSFilter(),ChannelProcessingFilter.class)
        .authorizeRequests().antMatchers("/rest/**").permitAll()
        .and().logout().logoutRequestMatcher(new AntPathRequestMatcher("/logout"))
        .logoutSuccessUrl("/index.html")        
        .and().exceptionHandling().authenticationEntryPoint(authenticationEntryPoint)       
        .and().formLogin().successHandler(authenticationSuccessHandler)
        .and().formLogin().failureHandler(authenticationFailureHandler)         
        .and().csrf().disable();
    }

@Autowired
    public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {

        auth.userDetailsService(userDetailsService).passwordEncoder(new BCryptPasswordEncoder());
    }
}

SimpleCORSFilter.java

public class SimpleCORSFilter implements Filter {
@Override
    public void doFilter(ServletRequest req,ServletResponse res,FilterChain chain) throws IOException,ServletException {
        HttpServletRequest request = (HttpServletRequest) req;
        HttpServletResponse response = (HttpServletResponse) res;

        response.setHeader("Access-Control-Allow-Origin","*");
        response.addHeader("Access-Control-Allow-Credentials","true");
        response.setHeader("Access-Control-Allow-Methods","POST,GET,PUT,OPTIONS,DELETE");
        response.setHeader("Access-Control-Max-Age","3600");
        response.setHeader("Access-Control-Allow-Headers","Origin,X-Requested-With,Content-Type,Accept");

        chain.doFilter(req,res);
    }

    @Override
    public void init(FilterConfig filterConfig) {

    }

    @Override
    public void destroy() {

    }
}

的login.html

<form>
<div class="rb-form-group" ng-class="{ 'has-error' : userForm.username.$invalid && !userForm.username.$pristine }">
            <input type="text" name="username" class="form-control" ng-model="credentials.username" placeholder="enter your username" required>
        </div>

        <!-- PASSWORD -->
        <div class="rb-form-group" ng-class="{ 'has-error' : userForm.password.$invalid && !userForm.password.$pristine }">
            <input type="password" name="password" class="form-control" ng-model="credentials.password" placeholder="enter your password" required>        
        </div>

        <div class="rb-form-group">
            <button class="btn btn-primary btn-block" ng-disabled="userForm.$invalid" ng-click="login()">Login</button>        
        </div>
</form>

提前致谢

网络日志

Remote Address:[::1]:8421
Request URL:http://localhost:8421/login
Request Method:POST
Status Code:200 OK
Response Headers
view source
Access-Control-Allow-Credentials:true
Access-Control-Allow-Credentials:true
Access-Control-Allow-Headers:Origin,Accept
Access-Control-Allow-Methods:POST,DELETE
Access-Control-Allow-Origin:*
Access-Control-Max-Age:3600
Cache-Control:no-cache,no-store,max-age=0,must-revalidate
Content-Length:0
Date:Tue,17 Nov 2015 04:01:57 GMT
Expires:0
Pragma:no-cache
Server:Apache-Coyote/1.1
Set-Cookie:JSESSIONID=D22C05E81D4FC86EA32BD6545F2B37FF; Path=/; HttpOnly
X-Content-Type-Options:nosniff
X-Frame-Options:DENY
X-XSS-Protection:1; mode=block
Request Headers
view source
Accept:application/json,text/plain,*/*
Accept-Encoding:gzip,deflate
Accept-Language:en-US,en;q=0.8
Connection:keep-alive
Content-Length:31
content-type:application/x-www-form-urlencoded
Host:localhost:8421
Origin:http://localhost:9000
Referer:http://localhost:9000/src/
User-Agent:Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML,like Gecko) Chrome/46.0.2490.86 Safari/537.36

解决方法

就CORS问题而言,请将授权和客户端安全令牌添加到Access-Control-Allow-Headers标头,如下所示.

response.setHeader("Access-Control-Allow-Headers","x-requested-with,origin,authorization,accept,client-security-token");

如果您的CORS过滤器配置正确,这应该可以正常工作!

要在spring security中使用基于AJAX的登录,您可能需要遵循稍微不同的方法.这在这里解释:

> Spring security 3 Ajax login – accessing protected resources
> Implementing Ajax Authentication

希望它有所帮助,随时评论任何问题!

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读