使用Spring安全性和Ajax自定义登录框

时间:2017-11-04 21:06:21

标签: ajax spring spring-security

我有一个登录框,这是我网站上的一个弹出窗口,我在配置spring security和AJAX调用登录和验证方面遇到了一些问题。我不确定我是否正确设置了它,我当前收到401()错误并且达到了login.js的严重错误,这是未经授权的访问和/ user / login方法没被叫......关于如何在spring安全性中处理AJAX登录和身份验证过程的基本概念将是很好的,包括安全配置。

HTML

    <form onSubmit="login()" id="notifyMe" method="POST" role="form">
        div class="form-group">
              <div class="controls">                                    
                  <!-- Field  -->
                                        <input type="text" id="username" name="username" placeholder="Enter your username" onfocus="this.placeholder = ''" onblur="this.placeholder = 'Click here to write your username'" class="form-control email srequiredField" />
                                        <input type="password" id="password" name="password" placeholder="Enter your password" onfocus="this.placeholder = ''" onblur="this.placeholder = 'Click here to write your password'" class="form-control email srequiredField" />                             
                                        <!-- Spinner top left during the submission -->
                                        <i class="fa fa-spinner opacity-0"></i>
                                        <!-- Button -->
                                        <button id="login-btw" class="btn btn-lg submit">LOG IN</button>
                                        <div class="clear"></div>        
        </div>        
     </div>        
</form>

AJAX

function login() {

console.info("Attempting to authenticate");

$.ajax({
    type: 'POST',
    url: '/user/login',
    data: $('#notifyMe').serialize(),
    cache: false,
    dataType: "json",
    contentType: "application/json;charset=utf-8",
    beforeSend:function(xhr) {
        xhr.setRequestHeader('X-Requested-With', 'XMLHttpRequest');
      },
    crossDomain: false,
    success: function (data) {
        var response = jQuery.parseJSON(data);
        if (response == true) {
            $(".message").html('<p class="notify-valid">Logging in...</p>').fadeIn();
            window.location.reload();
            console.info("Authentication Success!");
        }
        else {
            console.error("Unable to login");
            console.log(response);
            $(".message").html('<p class="notify-valid">Your log in details are incorrect. Please try again.</p>').fadeIn();
        }
    },
    error: function (data) {
        console.error("Critical error");
        console.log(data);
    }
});

SPRING SECURITY CONFIG

@Configuration
@EnableWebSecurity
public class SpringSecurityConfigurer extends WebSecurityConfigurerAdapter{

//Used in context with custom log in form (no /j_spring_security_check)
@Autowired
private CustomAuthenticationProvider cap;   

@Autowired
private AjaxAuthenticationSuccessHandler successHandler;

@Autowired
private AjaxAuthenticationFailureHandler failureHandler;

@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
    auth.authenticationProvider(cap);
}

@Bean(name = "requestCache")
public RequestCache getRequestCache() {
    return new HttpSessionRequestCache();
}

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

    http
        .authorizeRequests()
             //CSS FILES AND IMAGES
            .antMatchers("/fonts/**", "/css/**", "/img/**", "/js/**", "/admin/css/**", "/admin/img/**", "/admin/js/**" ).permitAll()
             //PAGES FOR ALL PEOPLE
            .antMatchers("/user/login", "/", "/user/**", "/register/**").permitAll()
             //PAGES FOR ADMIN
            .antMatchers("/admin/").access("hasAuthority('ROLE_ADMIN')")
            .antMatchers("/admin/**").access("hasAuthority('ROLE_ADMIN')")               
             //PAGES FOR USERS
            .antMatchers("/event/**").access("hasAuthority('ROLE_USER')")
            .anyRequest().authenticated()
        .and()
        .formLogin()
        .loginPage("/")
        .loginProcessingUrl("/user/login")
        .failureHandler(failureHandler)
        .successHandler(successHandler)
        .and()
        .csrf().disable()
        .logout().logoutRequestMatcher(new AntPathRequestMatcher("/user/logout"))
        .logoutSuccessUrl("/")
        .and().exceptionHandling().accessDeniedPage("/")
        //.authenticationEntryPoint(ajaxEntryPoint);
    ;
}

}

回复标题

    pragma: no-cache
date: Sun, 05 Nov 2017 11:08:12 GMT
x-content-type-options: nosniff
x-frame-options: DENY
content-type: application/json;charset=UTF-8
cache-control: no-cache, no-store, max-age=0, must-revalidate
transfer-encoding: chunked
x-xss-protection: 1; mode=block
expires: 0

js console image

0 个答案:

没有答案