首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >使用ajax登录和表单登录的2

问使用ajax登录和表单登录的2
EN

Stack Overflow用户
提问于 2015-11-24 06:16:02
回答 1查看 2.7K关注 0票数 1

开发一个需要REST身份验证和表单登录的应用程序。目前,使用ajax登录的2可以工作。在随后的请求中,可以发送“授权承担者”,服务器成功地授权请求。

登录/登录的Ajax代码

代码语言:javascript
复制
function signIn() {
            $.ajax({
            type : 'POST',
            url : 'oauth/token',
            data : {
                'client_id' : 'XXXXX',
                'client_secret' : 'YYYYYY',
                'grant_type' : 'password',
                'username' :encodeURIComponent($('#login').val()),
                'password' : encodeURIComponent($('#password').val()),
                'scope' : 'read write'
            },
             beforeSend: function(xhr) {
                 xhr.setRequestHeader("Authorization", "Basic " + $.base64.encode("XXXXX" + ':' + "YYYYYY") )
               },
            success : function(response) {
                 var expiredAt = new Date();
                    expiredAt.setSeconds(expiredAt.getSeconds() + response.expires_in);
                    response.expires_at = expiredAt.getTime();
                    localStorage.setItem('ls.token', JSON.stringify(response));
                    $.cookie("Authorization", "Bearer " + JSON.parse(localStorage.getItem("ls.token")).access_token );
                    var link = /*[[@{/}]]*/;
                    $(location).attr('href',link);
            }
        });
    }

在随后的AJAX请求中,授权包括在

代码语言:javascript
复制
  $.ajax({
       url: 'api/ZZZZZ/',
       type: 'GET',
     beforeSend: function(xhr) {
       xhr.setRequestHeader("Authorization", "Bearer " + JSON.parse(localStorage.getItem("ls.token")).access_token )
     },
       success: function(data) {}

在进行AJAX调用时,我可以看到请求头中的授权承担者。

代码语言:javascript
复制
 Accept */*
 Accept-Encoding    gzip, deflate
 Accept-Language    en-US,en;q=0.5
 Authorization  Bearer 49ef5d34-88a2-4e20-bd7a-87042c6a62b4
 Cache-Control  max-age=0
 Connection keep-alive
 Host   localhost:8080
 Referer    http://localhost:8080/productview?productId=19
 User-Agent Mozilla/5.0 (Macintosh; Intel Mac OS X 10.11; rv:42.0)      Gecko/20100101 Firefox/42.0
 X-Requested-With   XMLHttpRequest

我的春季安全配置看起来就像

代码语言:javascript
复制
  package com.geekyworks.equip.wowperks.config;

  import javax.inject.Inject;

  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.authentication.builders.AuthenticationManagerBuilder;
  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.EnableWebSecurity;
  import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
  import org.springframework.security.core.userdetails.UserDetailsService;
  import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
  import org.springframework.security.crypto.password.PasswordEncoder;
  import org.springframework.security.data.repository.query.SecurityEvaluationContextExtension;

  @Configuration
  @EnableWebSecurity
  @EnableGlobalMethodSecurity(prePostEnabled = true, securedEnabled = true)
  public class SecurityConfiguration extends WebSecurityConfigurerAdapter {

 @Inject
 private UserDetailsService userDetailsService;

@Bean
public PasswordEncoder passwordEncoder() {
    return new BCryptPasswordEncoder();
}

@Inject
public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
    auth
        .userDetailsService(userDetailsService)
            .passwordEncoder(passwordEncoder());
}

@Override
public void configure(WebSecurity web) throws Exception {
    web.ignoring()
        .antMatchers("/scripts/**/*.{js,html}")
        .antMatchers("/bower_components/**")
        .antMatchers("/i18n/**")
        .antMatchers("/assets/**")
        .antMatchers("/swagger-ui/index.html")
        .antMatchers("/api/register")
        .antMatchers("/api/activate")
        .antMatchers("/api/account/reset_password/init")
        .antMatchers("/api/account/reset_password/finish")
        .antMatchers("/api/home/**")
        .antMatchers("/api/product/**")
        .antMatchers("/test/**")
        .antMatchers("/devadmin/**")
        .antMatchers("/signin")
        .antMatchers("/static/api-guide.html");
}


@Order(67) // LOWEST
@Configuration
public static class NoAuthConfigurationAdapter extends WebSecurityConfigurerAdapter {
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http
        .antMatcher("/**")
        .authorizeRequests()
        .anyRequest()
        .permitAll();
    }
}

@Override
@Bean
public AuthenticationManager authenticationManagerBean() throws Exception {
    return super.authenticationManagerBean();
}

@Bean
public SecurityEvaluationContextExtension securityEvaluationContextExtension() {
    return new SecurityEvaluationContextExtension();
}

}

对于所有正常的http请求,即使在登录后,我也总是以“anonymousUser”的形式获得spring用户。

普通的http请求头(非AJAX)在请求头中不包含授权承载

代码语言:javascript
复制
      Accept    text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
      Accept-Encoding   gzip, deflate
      Accept-Language   en-US,en;q=0.5
      Cache-Control max-age=0
      Connection    keep-alive
      Cookie    Authorization=Bearer%2049ef5d34-88a2-4e20-bd7a-87042c6a62b4
      Host  localhost:8080
      Referer   http://localhost:8080/
      User-Agent    Mozilla/5.0 (Macintosh; Intel Mac OS X 10.11; rv:42.0) Gecko/20100101 Firefox/42.0

相反,它包含作为Cookie信息的授权持有者。我在AJAX登录后添加了cookie信息。

您知道如何使表单和AJAX身份验证在单个应用程序中使用security同时工作吗?

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2015-11-24 09:24:58

spring安全管理基于表单的身份验证的方式与通过oauth2.0实现的完全不同。当您使用ajax (oauth2.0)方式对用户进行身份验证(这实际上是用户使用用户名和密码的客户端应用程序的授权过程)时,只有您的客户端应用程序(您正在发出ajax请求的应用程序)将通过spring安全筛选器进行身份验证,而SecurityContextHolder将具有经过身份验证的客户端应用程序的身份验证对象,而不是用户。如果您将看到您的安全配置,那么在非ajax登录的情况下,您将允许所有请求在没有身份验证的情况下通过。要启用基于表单的登录,您需要配置您的安全性以保护除登录url以外的所有其他url。如下所示的东西

代码语言:javascript
复制
@Override
    protected void configure(HttpSecurity http) throws Exception {
        http.csrf().disable().authorizeRequests()
                .antMatchers("/**")
                .authenticated().and().formLogin();
    }
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/33886678

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档