如何在Spring Security后端从Angular应用正确验证用户身份

时间:2019-10-18 07:37:34

标签: java spring-boot spring-security angular8 angular-httpclient

我正在尝试在受Spring Security保护的Spring Boot 2.1后端对Angular 8应用程序进行身份验证。根据Active Directory检查用户请求。如果用户可以通过身份验证,我想返回一个包含响应用户名和授权的JSON响应。我通常要设置一个cookie。 我设法解决了cors问题,并且可以使用Postman得到正确的响应。 但是我在Angular应用程序中无法获得正确的信息。

Spring Boot

LoginController.java

@RestController
@CrossOrigin(origins = "http://localhost:4200", allowCredentials = "true")
@RequestMapping("/login")
public class LoginController {
    SecurityContext context;
    Authentication authentication;
    Collection<GrantedAuthority> grantedAuthorities;
    String cips_authorities = "";

    @GetMapping(value = "/loginPage")
    public String loginPage() {
        String loginForm = "<html >\n " +
        "<head></head>\n" +
                "<body>\n" +
                "   <h1>Login</h1>\n" +
                "   <form name='f' action=\"/login/loginPage\" method='post'>\n" +  // @{/login}
                "      <table>\n" +
                "         <tr>\n" +
                "            <td>User:</td>\n" +
                "            <td><input type='text' name='username' id='username' value=''></td>\n" +
                "         </tr>\n" +
                "         <tr>\n" +
                "            <td>Password:</td>\n" +
                "            <td><input type='password' name='password' id='password' /></td>\n" +
                "         </tr>\n" +
                "         <tr>\n" +
                "            <td><input name=\"submit\" type=\"submit\" value=\"submit\" /></td>\n" +
                "         </tr>\n" +
                "      </table>\n" +
                "  </form>\n" +
                "</body>\n" +
                "</html>";

        return loginForm;
    }
    @GetMapping(value = "/successful")
    public String successful(HttpServletResponse response) {

        response.setHeader("Access-Control-Allow-Origin", "*");
        context = SecurityContextHolder.getContext();
        authentication = context.getAuthentication();

        grantedAuthorities = (Collection<GrantedAuthority>) authentication.getAuthorities();
        cips_authorities = "";
        if (grantedAuthorities.toString().contains("CIPS_INVOICE")) {
            cips_authorities += ", \"CIPS_INVOICE\"";
        }
        if (grantedAuthorities.toString().contains("CIPS_STATS")) {
            cips_authorities += ", \"CIPS_STATS\"";
        }
        if (cips_authorities.length() > 2) {
            cips_authorities = "[" + cips_authorities.substring(2) + "]";
        }

        String userInformation = "{" +
                "\"userName\":\"" + authentication.getName() + "\"," +
                "\"authorities\":" + cips_authorities + "," +
                "\"authenticated\":\"" + authentication.isAuthenticated() + "\"" +
                "}";

        return userInformation;
    }

    @GetMapping(value = "/logout")
    public String logout() {
        context = SecurityContextHolder.getContext();

        String error = "{" +
                "\"userName\":\"" + authentication.getName() + "\"," +
                "\"authenticated\":\"" + authentication.isAuthenticated() + "\"" +
                "}";

        return error;
    }

    @GetMapping(value = "/active")
    public String active() {
        context = SecurityContextHolder.getContext();
        authentication = context.getAuthentication();

        String userInformation = "{" +
                "userName:" + authentication.getName() + "," +
                "authenticated:" + authentication.isAuthenticated() +
                "}";

        return userInformation;
    }

    @GetMapping(value = "/loggedOut")
    public String logedout() {
        context = SecurityContextHolder.getContext();
        authentication = context.getAuthentication();

        String userInformation = "{" +
                "\"session\":\"logged out\"" +
                "}";

        return userInformation;
    }

    @GetMapping(value = "/failed")
    public String failed() {
        context = SecurityContextHolder.getContext();
        authentication = context.getAuthentication();

        String error = "{" +
                "\"userName\":\"" + authentication.getName() + "\"," +
                "\"authenticated\":\"" + authentication.isAuthenticated() + "\"" +
                "}";

        return error;
    }

    @GetMapping(value = "/invalidSession")
    public String invalidSession() {
        String error = "{" +
                "\"session\":\"invalid\"" +
                "}";
        return error;
    }
}

BasicConfiguration.java

@Configuration
@EnableWebSecurity
//@EnableGlobalMethodSecurity(prePostEnabled = true)
public class BasicConfiguration extends WebSecurityConfigurerAdapter {

@Override
    protected void configure(HttpSecurity http) throws Exception {
        http.cors().and().csrf()
                .disable()
                .authorizeRequests()
                .antMatchers("/login/**")
                .permitAll()
                .antMatchers("/error/**")
                .permitAll()
                .anyRequest()
                .authenticated()
                .and()
                .formLogin()
                .defaultSuccessUrl("/login/successful", true)
                .and()
                .formLogin()
                .loginPage("/login/loginPage")
                .permitAll()
                .and()
                .formLogin()
                .failureUrl("/login/failed")
                .and()
                .logout()
                .and()
                .httpBasic()
                .and()
                .x509()
                .disable();

        http.logout()
                .logoutUrl("/login/logout")
                .logoutSuccessUrl("/login/loggedOut")
                .clearAuthentication(true)
                .deleteCookies("JSESSIONID")
                .invalidateHttpSession(true)
                .permitAll()
                .invalidateHttpSession(true);


        http.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.IF_REQUIRED);
        http.sessionManagement().maximumSessions(1);
        http.sessionManagement().invalidSessionUrl("/login/invalidSession");
        http.sessionManagement().sessionFixation().newSession();
    }

    @Bean
    public CorsConfigurationSource corsConfigurationSource () {
        CorsConfiguration corsConfiguration = new CorsConfiguration();
        corsConfiguration.setAllowedOrigins(Arrays.asList("*"));
        corsConfiguration.setAllowedMethods(Arrays.asList("GET", "POST"));
        corsConfiguration.setAllowedHeaders(Arrays.asList("authorization", "content-type", "x-auth-   token"));

        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        source.registerCorsConfiguration("/**", corsConfiguration);
        return source;
    }

}

邮递员结果

Request: 
Headers: 
  Content-Type: application/x-www-form-urlencoded
Body:
  username: <my-username>
  password: <my-password>

Response:
Headers:
  Date: Fri, 18 Oct 2019 06:44:50 GMT
  Access-Control-Allow-Origin: *
  Expires: Thu, 01 Jan 1970 00:00:00 GMT
  Content-Typ: text/plain;charset=utf-8"
  X-Content-Type-Options: nosniff
  X-XSS-Protection: 1; mode=block"
  X-Frame-Options: DENY
  Content-Lenght: 91
Cookies:
  Name: JSESSIONID
  Value: node01hidiu16ks9zn1owypmdrimsxw3.node0
Body:
  {"userName":"<my-username>","authorities":["CIPS_INVOICE", "CIPS_STATS"],"authenticated":"true"}

角度结果

Code for the request: 
const formdata = new FormData();
    formdata.append('username', username);
    formdata.append('password', password);

 this.http.post(`${environment.apiUrl}/login/loginPage`, formdata, {responseType: 'text'})
               .subscribe(res => {
                 console.log('response', res);
               });

Response:
response {"userName":"anonymousUser","authorities":,"authenticated":"true"}

我的问题:从Angular应用程序发送请求时,为什么我不能从广告中获取信息,尽管通过邮递员发送请求也可以得到它们? 而我该如何改变呢?

2 个答案:

答案 0 :(得分:0)

您需要明确告诉angular以获得完整的响应,而不仅仅是主体。

默认情况下,角度httpClient仅返回主体。为了获得完整的响应,您需要在httpOptions中添加
observe: 'response'这样的

var headers = new Headers();
    headers.append('Content-Type', 'application/json');
    let httpOptions = new RequestOptions({ headers: headers, withCredentials: true, observe: 'response' });

 return this.http.post(url, data, httpOptions)
   .subscribe(res => {
             console.log('response', res);
           });
 });

有关更多详细信息,请参见angular docs - reading full response

答案 1 :(得分:0)

我解决了这个问题: 这是服务器和客户端错误的组合。

我更改了以下内容:

LoginController.java:

successfull方法中,我删除了response.setHeader("Access-Control-Allow-Origin", "*")调用。

BasicConfiguration.java

corsConfigurationSource Bean中,我更改了AllowedOrigin策略: corsConfiguration.setAllowedOrigins(Arrays.asList("http://localhost:4200"))

并添加了AllowCredentials策略: corsConfiguration.setAllowCredentials(true)

角度

我将帖子调用更改为包括withCredentials:true

this.http.post(`${environment.apiUrl}/login/loginPage`, formdata,
                          {withCredentials: true})
               .subscribe(res => {
                 console.log(res);
               });

感谢所有回答并尝试提供帮助的人:)