小编Gio*_* K.的帖子

401发送获取用户令牌的请求时,由于CORS而未授权

最近我开始实现一个带有angularjs和spring mvc的基于令牌的安全系统.其思路如下:1.访问/ user/authenticate获取安全令牌并将令牌保存到本地存储2.对于angularJS客户端发送的每个请求,使用拦截器将X-Auth-Token头注入请求.

在我的Spring后端,我实现了AuthenticationTokenProcessingFilter和CustomAuthenticationEntryPoint.第一个用于从标头中提取令牌并检查它是否有效,第二个用于在未对请求进行身份验证时返回401未授权状态.

请查找有关我的后端代码的一些详细信息

AuthenticationController.java

@RestController
@RequestMapping(value="user")
public class AuthenticationController {

    @RequestMapping(value="authenticate", method = RequestMethod.POST)
    public ResponseEntity<?> login(@RequestParam("email") String email, 
        @RequestParam("password") String password) {
             //Check if user is valid and return token
        }
}
Run Code Online (Sandbox Code Playgroud)

SecurityConfig.java

public class SecurityConfig extends WebSecurityConfigurerAdapter {

@Autowired
UsersRepository usersRepo;

@Autowired
public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {...}

@Override
protected void configure(HttpSecurity http) throws Exception {
    http
        .addFilterBefore(
                    new AuthenticationTokenProcessingFilter(usersRepo),
                    UsernamePasswordAuthenticationFilter.class)
        .addFilterBefore(this.corsFilter(), UsernamePasswordAuthenticationFilter.class)
            .sessionManagement()
            .sessionCreationPolicy(SessionCreationPolicy.STATELESS)
        .and()
            .csrf().disable().exceptionHandling()
        .and()
            .httpBasic()
            .authenticationEntryPoint(new CustomAuthenticationEntryPoint())
        .and()
            .authorizeRequests()
            .antMatchers(HttpMethod.POST, "/user/authenticate").permitAll() …
Run Code Online (Sandbox Code Playgroud)

authentication spring-mvc cors angularjs

7
推荐指数
1
解决办法
9014
查看次数

标签 统计

angularjs ×1

authentication ×1

cors ×1

spring-mvc ×1