簡體   English   中英

如何使用 Angular + Spring + JSON 自定義登錄/身份驗證

[英]How to custom Login / authenticate with Angular + Spring + JSON

我有一個 angular 7 前端和 Spring 后端。

我的目標是使用 JSON 表單進行自定義登錄。 計划:將用戶名/密碼以 json 形式從前端發送到后端。 在后端進行身份驗證,並將結果發送回前端。 我的問題:從前端發送數據后,我看不到后端的數據(用戶名和密碼為空)(在我的 CustomAuthenticationProvider.java 中)

我的登錄頁面 function:

let credential = {username: this.loginForm.value.username, password: this.loginForm.value.password};

if(this.loginForm.value.username != null && this.loginForm.value.password != null) {
     this.http.post("auth", JSON.stringify(credential)).subscribe(
           response => {
                if(response.status == 200 && response.ok == true) {
                   this.globals.loggeduser = this.loginForm.value.username;
                   //and routing
                } else {
                     alert("Bad credential");
           } 
     );
}
@Component
public class CustomAuthenticationProvider implements AuthenticationProvider {

    public CustomAuthenticationProvider() {
        super();
    }

    @Override
    public Authentication authenticate(final Authentication authentication) throws AuthenticationException {
        final String username = authentication.getName();
        final String password = authentication.getCredentials().toString();

 //THE PROBLEM: username and password are empty here

            if (/* some custom auth here */) {
                final List<GrantedAuthority> grantedAuths = new ArrayList<>();
                grantedAuths.add(new SimpleGrantedAuthority("ROLE_USER"));
                final UserDetails principal = new User(username, password, grantedAuths);
                final Authentication auth = new UsernamePasswordAuthenticationToken(principal, password, grantedAuths);
             
                return auth;
            }

        return null;
    }

    @Override
    public boolean supports(Class<?> authentication) {
        return UsernamePasswordAuthenticationToken.class.isAssignableFrom(authentication);
    }

}
@Configuration
@EnableWebSecurity
public class SecurityConfiguration extends WebSecurityConfigurerAdapter {

    @Autowired
    private CustomAuthenticationProvider customAuthenticationProvider;

    @Override
    protected void configure(final AuthenticationManagerBuilder auth) throws Exception {
        auth.authenticationProvider(customAuthenticationProvider);
    }

    @Override
    protected void configure(final HttpSecurity http) throws Exception {
        http.csrf().disable()
            .authorizeRequests()
            .antMatchers(HttpMethod.GET,"/login", "/index*", "/static/**", "/*.js", 
                                        "/*.json", "/*.ico", "/*.sccs", "/*.woff2", "/*.css").permitAll()
            .anyRequest()
                .authenticated()
                .and()
            .formLogin()
                .loginPage("/")
                .loginProcessingUrl("/auth")
                .usernameParameter("username")
                .passwordParameter("password")
                .successHandler(successHandler())
                .failureHandler(failureHandler())
                .permitAll()
                .and()
            .logout()
                .permitAll();
    }

    private AuthenticationSuccessHandler successHandler() {
       ...
    }

    private AuthenticationFailureHandler failureHandler() {
       ...
    }
}

當我在向用戶名和密碼添加值后打印出authentication時,我得到了這個(主體和憑據為空):

org.springframework.security.authentication.UsernamePasswordAuthenticationToken@b37b: Principal: ; Credentials: [PROTECTED];
Authenticated: false; Details: org.springframework.security.web.authentication.WebAuthenticationDetails@b364:
RemoteIpAddress: 0:0:0:0:0:0:0:1; SessionId: null; Not granted any authorities

不使用 JSON 格式可以正常工作,但我需要使用 JSON 格式。 我讀了這個這個(我嘗試了這些解決方案,沒有用)。 這些有點過時而且不好(太復雜和/或 xml 格式)我讀到我必須編寫一個自定義的 UsernamePasswordAuthenticationFilter / 使用 Beans,但我想做一個漂亮而干凈的 java 解決方案而不重新工作整個事情/ 使用 xml。 請問我可以得到一些幫助/提示嗎?

編輯:使用這種格式(而不是let credential =... ),它正在工作(但不幸的是它不是 JSON ):

let urlSearchParams = new URLSearchParams();
urlSearchParams.append('username', this.loginForm.value.username );
urlSearchParams.append('password', this.loginForm.value.password );

我找到了解決方案。

我添加了一個 CustomAuthenticationFilter,將 go 歸功於 @oe.elvik 在這個問題中的回答。 (注意:LoginRequest 是一個 class 有 2 個變量:用戶名和密碼)之后,我將其添加到我的 securityConfig 中,一切正常:

@Bean
public CustomAuthenticationFilter customAuthenticationFilter() throws Exception{
    CustomAuthenticationFilter customAuthenticationFilter = new CustomAuthenticationFilter();
    customAuthenticationFilter.setAuthenticationManager(authenticationManager());
    customAuthenticationFilter.setFilterProcessesUrl("/auth");
    customAuthenticationFilter.setAuthenticationSuccessHandler(successHandler());
    customAuthenticationFilter.setAuthenticationFailureHandler(failureHandler());

    return customAuthenticationFilter;
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM