繁体   English   中英

如何将凭据从Angular2前端传递到Spring后端(带有Spring Security的基本身份验证)

[英]How can I pass credentials from Angular2 frontend to Spring backend (Basic-Authentification with Spring Security)

我正在开发一个使用spring作为后端,angular2作为前端的应用程序, Backside端是安全的(使用Spring security ),并且在运行它时具有默认的登录表单。 我想从客户端登录到服务器端,但是当我尝试传递凭据时,在浏览器控制台中出现这些错误

配置类

@Configuration
@EnableWebSecurity

public class WebSecurityConfig extends WebSecurityConfigurerAdapter {

    @Autowired
    public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
        auth.inMemoryAuthentication().withUser("admin").password("admin").roles("ADMIN", "USER").and().withUser("user")
                .password("user").roles("USER");
    }

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

        http
        .csrf().disable()
        .authorizeRequests()
        .antMatchers("/etudiant/list").hasRole("ADMIN")
            .anyRequest().authenticated()
            .and()
        .formLogin()
        .and()
        .httpBasic();
    }

}

web.xml中的安全过滤器:

<filter>
    <filter-name>springSecurityFilterChain</filter-name>
        <filter-class>
        org.springframework.web.filter.DelegatingFilterProxy
        </filter-class>
  </filter>
  <filter-mapping>
    <filter-name>springSecurityFilterChain</filter-name>
    <url-pattern>/*</url-pattern>
  </filter-mapping>

angular2侧的登录表单:

 <div class="login jumbotron center-block"> <h1>Login</h1> <form role="form" (submit)="login(username.value, password.value)"> <div class="form-group"> <label for="username">Username</label> <input type="text" #username class="form-control" id="username" placeholder="Username"> </div> <div class="form-group"> <label for="password">Password</label> <input type="password" #password class="form-control" id="password" placeholder="Password"> </div> <button type="submit" class="btn btn-default">Submit</button> </form> </div> 

我将使用@Injectable()调用的以下方法创建@Injectable() AuthService。

login(usercreds) {
  const headers = new Headers();
  const creds = 'name=' + usercreds.username + '&password=' + usercreds.password;

  headers.append('Content-Type', 'application/x-www-form-urlencoded');

  return new Promise((resolve) => {
    this.http.post('http://localhost:3333/authenticate', creds, {headers: headers}).subscribe((data) => {
        if (data.json().success) {
          // window.localStorage.setItem('auth_key', data.json().token);
          this.userId = data.json().userId;
          this.isAuthenticated = true;
        }
        resolve(this.isAuthenticated);
     });
  });
}

不要忘记在app.module.ts文件中将此组件声明为提供程序

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM