【问题标题】:Spring Security : impossible to do Authentication in front end sideSpring Security:无法在前端进行身份验证
【发布时间】:2019-06-14 00:50:05
【问题描述】:

我有一个 Spring Boot 后端和一个基于 Angular 5 的前端。 我想使用 Spring Security 进行身份验证和授权。 我希望在 Angular(http://localhost:4200/login) 中自定义登录表单。 我想在数据库中有用户及其密码和角色。 我不明白如何告诉 Spring 登录页面位于不同的域中(在前端)。 我应该在 RestController 类中定义一个 /login 还是在 Spring Security 中默认有一个 /login 允许对用户进行身份验证? 请帮忙。

我从测试配置开始:内存中的用户:

package smart.syndic.security;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpMethod;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;

@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter
{   

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception 
    {   
        auth.inMemoryAuthentication()
            .withUser("admin").password("1234")
            .roles("ADMIN");
    }

    @Bean
    public BCryptPasswordEncoder bCryptPasswordEncoder()
    {
        return new BCryptPasswordEncoder();
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception 
    {
        http.csrf().disable();
        http.authorizeRequests()
            .antMatchers("/login/**", "/administrateurs/**").permitAll()
            .and()
            .authorizeRequests().antMatchers(HttpMethod.GET, "/users").permitAll()
            .and()
            .exceptionHandling().accessDeniedPage("/forbidden")
            .and()
            .authorizeRequests().anyRequest().authenticated();

    }
}

【问题讨论】:

标签: java angular spring-boot spring-security


【解决方案1】:

如果您选择将后端和前端拆分到 2 个不同的服务器(例如 localhost:8080 和 localhost:4200),那么假设后端对前端一无所知会更优雅。在这种方法中,当请求未经授权时,后端应返回状态 401 (like here),您的前端应处理此问题,将用户重定向到 /login 页面。

为了在春天做到这一点,你可以像评论中的例子那样做。

  1. 实施filter
  2. 告诉 spring 使用这个过滤器,就像这里 WebSecurityConfig
  3. Create controller for login

【讨论】:

    猜你喜欢
    • 2014-02-01
    • 2016-09-13
    • 2021-11-25
    • 2011-04-30
    • 2012-11-27
    • 2019-02-07
    • 1970-01-01
    • 2011-10-17
    相关资源
    最近更新 更多