angular 2 login with spring security

随声附和 提交于 2019-12-04 09:25:55

Once you're working with the API, you've to use either HTTP Basic or token authentication and not Form one. It's required to use HTTPS when using any of them.

To auth in HTTP Basic way using Angular 2 the login service may look like this:

login (loginDetails: any): Observable<LoginResponse> { // custom class, may be empty for now

    let headers = new Headers({ 
          'Authorization': 'Basic ' + btoa(loginDetails.login + ':' + loginDetails.pass),
          'X-Requested-With': 'XMLHttpRequest' // to suppress 401 browser popup
    });

    let options = new RequestOptions({ 
           headers: headers 
    });

    return this
              .http
              .post(this.loginUrl, {}, options)
              .catch(e => this.handleError(e); // handle 401 error - bad credentials
}

... then you can subscribe this in a component:

loginNow() {
   this
     .loginService
     .login(this.loginDetails)
     .subscribe(next => {
        this.router.navigateByUrl("/"); // login succeed
     }, error => {
        this.error = "Bad credentials"; // or extract smth from <error> object
     });
}

Then you can use the loginNow() method inside the component templates like this (click)="loginNow().

Once the server will accept the authorization, JSESSIONID will be stored in your browser automatically because of Spring Security features and you won't be forced to send the credential details each time in order to access private resources.

Your login server method may look like this:

@PreAuthorize("hasRole('USER')")
@PostMapping("/login")
public ResponseEntity login() {
    return new ResponseEntity<>(HttpStatus.OK);
}

... it will reject with 401 UNAUTHORIZED once the authorization fails or accept with 200 SUCCESS if it won't.

How to setup the server in the proper way there's a number of Spring Security demo projects - https://github.com/spring-guides/tut-spring-security-and-angular-js

the code isn't tested though :(

Your spring security config needs to look like this

 http!!
     .cors().and()
     .csrf().disable()
    .authorizeRequests()
     .requestMatchers(object: RequestMatcher {
       override fun matches(request: HttpServletRequest?): Boolean {
         return CorsUtils.isCorsRequest(request)
       }
     }).permitAll()
    .antMatchers("/api/**").authenticated()
    .anyRequest().permitAll()
    .and()
    .formLogin().permitAll()

I had a similar issue, but I had to override the successlogout handler as mentioned here.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!