如何实现spring security config从角度站点调用授权

时间:2015-11-01 20:07:05

标签: java angularjs spring spring-security

我尝试使用角度$http从网站进行授权,弹簧WebSecurityConfigurerAdapter这是我的代码:

Java部分:

    @Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    private static final Logger LOGGER = Logger.getLogger(SecurityConfig.class);

    @Autowired
    private UserDetailsService customUserDetailsService;

    @Autowired
    public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
        // auth.inMemoryAuthentication().withUser("user").password("12345").roles("USER");
        auth.userDetailsService(customUserDetailsService);
    }

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

        CsrfTokenResponseHeaderBindingFilter bindingFilter = new CsrfTokenResponseHeaderBindingFilter();
        http.addFilterAfter(bindingFilter, CsrfFilter.class);

        http.authorizeRequests().antMatchers("/", "/home").permitAll()
                .anyRequest().authenticated().and().formLogin().defaultSuccessUrl("/")
                .loginProcessingUrl("/authenticate").usernameParameter("username").passwordParameter("password")
                .successHandler(new AjaxAuthenticationSuccessHandler(new SavedRequestAwareAuthenticationSuccessHandler()))
                .loginPage("/login/existinguser").and().httpBasic().and().logout().logoutUrl("/logout")
                .logoutSuccessUrl("/login/existinguser").permitAll();

        if ("true".equals(System.getProperty("httpsOnly"))) {
            LOGGER.info("launching the application in HTTPS-only mode");
            http.requiresChannel().anyRequest().requiresSecure();
        }
    }
}

JS部分:

  $scope.login = function (username, password) {
        var postData = 'username='+username+'&password='+password;

        $http({
            method: 'POST',
            url: '/authenticate',
            data: postData,
            headers: {
                "Content-Type": "application/x-www-form-urlencoded",
                "X-Login-Ajax-call": 'true'
            }
        })
        .then(function(response) {
            if (response.data == 'ok') {
                debugger;
                window.location.replace('/');

            }
            else {
                debugger;
            }
        });
    };

问题是我收到错误:

POST http://localhost:8080/authenticate 404 (Not Found)

有人可以说我需要做什么,让它发挥作用吗?

3 个答案:

答案 0 :(得分:0)

您好,您必须配置身份验证休息服务here您在Spring启动身份验证中有完整的休息身份验证教程 - 示例使用jquery但是将js部分更改为angular

答案 1 :(得分:0)

我认为问题在于csrf令牌。如果你确定你的控制器,post方法,那么你应该将csrf标记添加到ajax调用的标题中;

var token = $("input[name='_csrf']").val();
var header = "X-CSRF-TOKEN";
$(document).ajaxSend(function(e, xhr, options) {
    xhr.setRequestHeader(header, token);
});

或者您可以在SecurityConfig类中禁用csrf令牌。

答案 2 :(得分:0)

您可以在login.ftl文件中执行登录表单,如:

    <#-- @ftlvariable name="_csrf" type="org.springframework.security.web.csrf.CsrfToken" -->
    <#-- @ftlvariable name="error" type="java.util.Optional<String>" -->

    <form role="form"  action="/login" method="post">
        <#--<label for="email">Email</label>-->
        <input type="text" name="email" id="email" placeholder="EMAIL" required autofocus/>
        <#--<label for="password">Password</label>-->
        <input type="password" name="password" id="password" placeholder="PASSWORD" required/>
        <button type="submit"> LOGIN </button>
    </form>

    <#if error.isPresent()>
        <p>The email or password you have entered is invalid, try again.</p>
    </#if>

在Java(安全)中:

@Override
protected void configure(HttpSecurity httpSecurity) throws Exception {
    httpSecurity
            .authorizeRequests()
            .antMatchers("/css/*").permitAll()
            .antMatchers("/images/*").anonymous()
            .antMatchers("/fonts/*").permitAll()
            .antMatchers("/bower_components/**").permitAll()
            .antMatchers("/scripts/**").permitAll()
            .antMatchers("/template/**").permitAll()
            .antMatchers("/views/**").permitAll()
            .anyRequest().authenticated()
            .and()
            .formLogin()
            .loginPage("/login")
            .failureUrl("/login?error")
            .usernameParameter("email")
            .permitAll()
            .and()
            .logout()
            .logoutUrl("/logout")
            .deleteCookies("remember-me")
            .logoutSuccessUrl("/login")
            .permitAll();
}

和控制器:

@RequestMapping(value = "/login", method = RequestMethod.GET)
public ModelAndView getLoginPage(@RequestParam Optional<String> error) {
    return new ModelAndView("login", "error", error);
}

这对我有用。我想,我帮助你。