当前位置: 首页 > 知识库问答 >
问题:

如何使用Angular Spring JSON自定义登录/身份验证

岳承悦
2023-03-14

我有一个角度7前端和Spring后端。

我的目标是使用JSON表单进行自定义登录。计划是:以json格式将用户名/密码从前端发送到后端。在后端进行身份验证,并将结果发送回前端。我的问题:从前端发送数据后,我在后端看不到数据(用户名和密码为空)(在我的CustomAuthenticationProvider.java中)

我的登录页面功能:

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() {
       ...
    }
}

当我在用户名和密码中添加值后打印出身份验证时,我得到这个(主体和凭据是空的):

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

使用not JSON格式很好,但我需要使用JSON格式。我读了这个和这个(我尝试了这些解决方案,但没有成功)。这些都有点过时,也不好(太复杂和/或xml格式),我读到我必须使用bean编写一个自定义用户名PasswordAuthenticationFilter/但我想做一个好的、干净的java解决方案,而不必重新设计整个过程/使用xml。我能得到一些帮助/提示吗?

编辑:使用这种格式(而不是let credential=…),它可以工作(但不幸的是它不是JSON):

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

共有1个答案

陶琦
2023-03-14

我找到了解决办法。

(注意:LoginRequest是一个有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;
}
 类似资料:
  • 在过去的几周里,我一直在努力掌握KeyClope,这样我就可以实现一种使用遗留提供商(基于Oracle,带有会话表和各种奇怪的东西)对用户进行身份验证的方法。我们计划在不久的将来解决这个问题,但目前我们必须解决这个问题,所以我们的想法是在前线使用KeyClope——利用它提供的主要好处,比如SSO——在需要身份验证的应用程序中省略传统的身份验证提供程序。 我读了一些关于构建自定义OIDC身份提供程

  • 我们希望使用外部身份提供者将现有的Spring Security项目从自定义用户名/密码实现(UserDetailsService等)迁移到oauth2登录。 但是,当通过外部提供程序登录时,安全上下文中的身份验证对象是一个,主体是一个。 由于我们在应用程序中使用的都是自定义身份验证主体,因此我们希望将转换为自定义对象。 对于oauth2资源服务器,似乎有一个API可让您将JWtAuthentia

  • 该应用程序应该接受用户电子邮件和密码,并使用Firebase身份验证作为后端。我使用像素2作为模拟器。每次应用程序处理登录功能时,它都会崩溃。 下面是Java文件和gradle文件 Java文件:

  • 使用,https://github.com/firebase/FirebaseUI-Android/tree/master/codelabs/chat作为登录的参考,我在键入时似乎遇到了问题 我只能键入Auth的提供者,而不能键入,为什么会这样,它提示我键入社会提供者。

  • 问题内容: 这是我的情况: 一个Web应用程序对许多应用程序执行某种SSO 登录的用户,而不是单击链接,该应用就会向正确的应用发布包含用户信息(名称,pwd [无用],角色)的帖子 我正在其中一个应用程序上实现SpringSecurity以从其功能中受益(会话中的权限,其类提供的方法等) 因此,我需要开发一个 自定义过滤器 -我猜想-能够从请求中检索用户信息,通过自定义 DetailsUserSe

  • 问题内容: 我正在按照auth0的教程使用JWT保护我的应用程序。 我完成了以下WebSecurity配置: 和以下JWTAuthenticationFilter: 目前,该应用接受URL 上的POST请求。我想知道如何将URL更改为。有什么方法可以将URL字符串注入到身份验证过滤器中,或以某种方式在安全配置中对其进行设置? 问题答案: 您正在扩展org.springframework.secur