【问题标题】:How to implement spring security config to call authorization from angular site如何实现弹簧安全配置以从角度站点调用授权
【发布时间】:2016-02-01 16:31:27
【问题描述】:

我尝试使用 angular $http 和 spring 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)

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

【问题讨论】:

  • 我做了tomcat配置,不需要名字。是的,我有这方面的控制器,只是不确定这是因为映射。感觉就像/authenticate 没有映射。
  • 是的,我有控制器

标签: java angularjs spring spring-security


【解决方案1】:

您可以在 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);
}

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

【讨论】:

    【解决方案2】:

    我认为问题出在 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 令牌。

    【讨论】:

      【解决方案3】:

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

      【讨论】:

        猜你喜欢
        • 2015-04-19
        • 2013-07-16
        • 2017-07-21
        • 2017-05-08
        • 2020-05-19
        • 2015-12-20
        • 2019-09-29
        • 2016-01-02
        相关资源
        最近更新 更多