Angularjs   发布时间:2022-04-20  发布网站:大佬教程  code.js-code.com
大佬教程收集整理的这篇文章主要介绍了具有跨源资源共享(CORS)的AngularJS spring安全登录/注销大佬教程大佬觉得挺不错的,现在分享给大家,也给大家做个参考。
问题陈述:我的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

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

大佬总结

以上是大佬教程为你收集整理的具有跨源资源共享(CORS)的AngularJS spring安全登录/注销全部内容,希望文章能够帮你解决具有跨源资源共享(CORS)的AngularJS spring安全登录/注销所遇到的程序开发问题。

如果觉得大佬教程网站内容还不错,欢迎将大佬教程推荐给程序员好友。

本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。