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

如何使用Spring Security登录/验证

司空鸿禧
2023-03-14

我正在尝试使用Spring boot 2.3.1 Spring security 7做一个webapp。现在,我的主要目标是,如果用户想要登录(使用定制的angular登录页面),前端会将数据(用户名和密码)发送到后端,我想在那里进行身份验证,并向前端发回一条消息(比如:OK message或其他)

我的项目是这样工作的:用maven我构建角前端,从“dist”文件夹中复制文件/文件夹并放入后端资源文件夹。有了这个解决方案,一切都正常,现在我想添加Spring安全部分。

SecurityConfig。JAVA

@Configuration
@EnableWebSecurity
public class SecurityConfiguration extends WebSecurityConfigurerAdapter {

    @Override
    protected void configure(final AuthenticationManagerBuilder auth) throws Exception {
        auth.inMemoryAuthentication()
        .withUser("user1").password("{noop}password123").roles("USER");
    }

    @Override
    protected void configure(final HttpSecurity http) throws Exception {
        http
        .csrf().disable()
        .authorizeRequests()
            //.antMatchers(HttpMethod.POST, "/auth").permitAll() // I tried this but nothing
            .antMatchers(HttpMethod.GET, "/login", "/index*", "/static/**", "/*.js", "/*.json", "/*.ico", "/*.sccs", "/*.woff2", "/*.css").permitAll()
            .anyRequest().authenticated()
            .and()
          .formLogin()
            .loginPage("/")
            .loginProcessingUrl("/auth")
            .usernameParameter("username")
            .passwordParameter("password")
            .failureUrl("/index.html?error=true")
            .permitAll();
    }
}

ApiController.java

@RestController
public class ApiController {

    @PostMapping("/auth")
    public boolean login(@RequestBody User user) {
        return user.getUserName().equals("user") && user.getPassword().equals("password"); // I would like to authenticate with auth.inMemoryAuthentication()
    }
}

我有一个User.java2个变量(用户名和密码)

登录。组件。ts

import { Component, OnInit } from '@angular/core';
import { Router } from '@angular/router';
import { FormGroup } from '@angular/forms';
import { LoggerService } from '@app/core/services/logger.service';
import { Http } from "@angular/http";

import { FormControlHelper, Globals } from '@app/core/helpers/index';
import { loginValidation } from '@app/models/form-validations/index';
import { HttpParams, HttpHeaders} from "@angular/common/http";
import { URLSearchParams } from "@angular/http"
import { MatSnackBar } from '@angular/material/snack-bar';

@Component({
    selector: 'app-login',
    templateUrl: './login.component.html',
})
export class LoginComponent implements OnInit {
    // Properties
    globals: Globals;
    public loginForm: FormGroup;
    public loginValidationModel: any;
    public waiting: boolean;
    public hidePassword: boolean;
    public params = new HttpParams();

    constructor(
        globals: Globals,
        private router: Router,
        private logger: LoggerService,
        public http : Http,
        private snackBar: MatSnackBar
    ) {
        this.loginValidationModel = loginValidation;
        this.hidePassword = true;
        this.globals = globals;

    }

    openSnackBar(message: string, action: string) {
        this.snackBar.open(message, action, {
          duration: 5000,
          verticalPosition: 'top', // 'top' | 'bottom'
                horizontalPosition: 'center', //'start' | 'center' | 'end' | 'left' | 'right'
                panelClass: ['red-snackbar'],
        });
      }

    ngOnInit() {
        const formGroupObj = FormControlHelper.generateFormControls(this.loginValidationModel);
        if (formGroupObj) {
            this.loginForm = new FormGroup(formGroupObj);
        } else {
            this.logger.error(new Error('Error generating the form modal & validations'));
        }

    }

    public onSubmit() {

       let urlSearchParams = new URLSearchParams();
       urlSearchParams.append('username', this.loginForm.value.username );
       urlSearchParams.append('password', this.loginForm.value.password );
       console.log("urlSearchParams: " + urlSearchParams);

       this.http.post("auth", urlSearchParams)
        .subscribe(
                response => {
                    if(response) { //Here I always get code 200 with "OK" status, even if the username/password is bad, I don't know how to fix this part
                        this.globals.loggeduser=this.loginForm.value.username;
                        this.router.navigateByUrl('/somewhere');
                    } else {
                        alert("Authentication failed");
                    }
                }
            );

    } 
}

我试过了https://spring.io/guides/tutorials/spring-security-and-angular-js/理解它(通过一些贝尔东教程),但我现在有点困惑。谁能帮帮我吗?谢谢你,祝你今天愉快。

编辑:我建立一个. war文件,并使用Tomcat。

编辑2:更多细节和一些进展。我展示了两个例子,一个是有效的,一个是无效的用户名/密码。如果用户名/密码无效,我可以看到url中有“错误”部分。我的问题是:尽管有错误,但在前端我可以登录,并且可以访问所有内容(子页面)。我该如何解决这个问题?(如果登录有效-

Edit3:我还有一个问题:如果我是正确的,使用loginProcessingUrl,我无法使用controller(映射到/auth)处理数据。所以在这种情况下是没用的,对吧?

共有1个答案

子车安和
2023-03-14

我找到了一个可能的解决办法。

我稍微修改了一下SecurityConfiguration.java(添加了setesHandler/故障处理程序)

证券配置。JAVA

@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() {
    return new AuthenticationSuccessHandler() {
        @Override
        public void onAuthenticationSuccess(HttpServletRequest httpServletRequest,
                HttpServletResponse httpServletResponse, Authentication authentication)
                throws IOException, ServletException {
            httpServletResponse.getWriter().append("OK");
            httpServletResponse.setStatus(200);
        }
    };
}

private AuthenticationFailureHandler failureHandler() {
    return new AuthenticationFailureHandler() {
        @Override
        public void onAuthenticationFailure(HttpServletRequest httpServletRequest,
                HttpServletResponse httpServletResponse, AuthenticationException e)
                throws IOException, ServletException {
            httpServletResponse.getWriter().append("Authentication failure");
            httpServletResponse.setStatus(401);
        }
    };
}

在那之后,我也改变了前端登录组件

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


    if(this.loginForm.value.username != null && this.loginForm.value.password != null) {
        this.http.post("auth", urlSearchParams).subscribe(
            response => {
                if(response.status == 200 && response.ok == true) {
                    this.globals.loggeduser=this.loginForm.value.username;
                    this.router.navigateByUrl('/somewhere');
                } else {
                    this.openSnackBar("Wrong username or password!","");
                }
            } 
        );
    }

在这些变化之后,一切都在运转。

 类似资料:
  • 我正在尝试使用Spring Security UserDetailService身份验证使用电子邮件而不是用户名登录,但我无法登录并获取 org.springframework.security.authentication.内部身份验证服务异常。 调试代码时,调试器不会跟踪 用户user=userDao。findByUserName(用户电子邮件);来自UserServiceImpl。java和

  • 目前,我正在使用以下内容将用户登录到我的应用程序中。然而,我想使用一个角函数来实际执行登录。为此,我想创建一个Rest网络服务来进行身份验证,但是我在SO上看到的所有示例都使用我认为被贬低的用户。我还希望该服务返回有关用户的信息。 我要问的是如何将MyUserDetailsService更改为用作登录的restful服务,或者如何创建一个可用于登录的服务,该服务将在登录后返回用户对象。 这是我的a

  • springsecurity oauth2.0 谁做过记录登录日志?监听事件好像没法区分是什么原因失败的、比如client错误还是用户名错误

  • 现在,使用这些标记,我在api文件中创建了一个函数,但它将<code>0 函数代码: 那么,如何使用WordPress hook<code>wp_get_current_user()获取登录用户数据呢? 其次,我如何使< code > jwt-auth/v1/token API动态获取用户名和密码? P. S我在htacceess文件中添加了ReWriteCond和ReWriteRur,并且在我的

  • 问题内容: 我们有一个Java EE 7应用程序,并使用Arquillian进行测试。现在,我们要检查当前登录用户的某些权限。我的问题很基本,在测试用例中时如何登录用户?我已经阅读了ProgrammaticLogin在Arquillian测试和Embedded Glassfish,安全性和Arquillian问题中不起作用,但是并没有明确回答。我当前的方法是这样的: 现在,当我尝试运行此命令时,将

  • 首先,我很抱歉在这里问这样的问题,但是如果您以前从未参与过symfony项目,symfony文档不会提供太多完整的示例。 因此,我已经安装了symfony/security包,并且在本教程中开始了类似的工作https://symfony.com/doc/current/security/form_login_setup.html 包裹/security.yaml 登录路径和检查路径是我的安全控制器