【问题标题】:How to authenticate a user with Spring Boot?如何使用 Spring Boot 对用户进行身份验证?
【发布时间】:2019-11-22 16:39:40
【问题描述】:

我已经设置了WebSecurityConfigurerAdapter,以便它将所有内容重定向到 /login URL,但是现在我对如何授予身份验证感到困惑?我有一个User.javaUserRepository.java 和一个UserService.java

我已经阅读了多篇关于如何使用 Spring Boot 进行基本身份验证的文章。他们唯一的共同点是他们使用 WebSecurityConfigurerAdapter 将用户重定向到登录页面。似乎有多种方法可以实现登录,我只想使用基本的UserController -> UserService -> UserRepo 方式来检索用户及其数据。这是我目前的代码。

网络安全配置


    package com.flashcards.flashcard;

    import org.springframework.context.annotation.Bean;
    import org.springframework.context.annotation.Configuration;
    import org.springframework.security.config.annotation.web.builders.HttpSecurity;
    import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
    import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
    import org.springframework.security.core.userdetails.User;
    import org.springframework.security.core.userdetails.UserDetails;
    import org.springframework.security.core.userdetails.UserDetailsService;
    import org.springframework.security.provisioning.InMemoryUserDetailsManager;

    @Configuration
    @EnableWebSecurity
    public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
        @Override
        protected void configure(HttpSecurity http) throws Exception {
            http
                .authorizeRequests()
                    .antMatchers("/").permitAll()
                    .anyRequest().authenticated()
                    .and()
                .formLogin()
                    .loginPage("/login")
                    .permitAll()
                    .and()
                .logout()
                    .permitAll();


        } 
    }

User.java


    package com.flashcards.flashcard;

    import lombok.Data;

    import java.util.List;

    import javax.persistence.Entity;
    import javax.persistence.GeneratedValue;
    import javax.persistence.Id; 
    import javax.persistence.OneToMany;

    @Data
    @Entity

    class User{
        private @Id @GeneratedValue long id;
        private String userName;
        private String password;
        private String passwordConfirm;
        @OneToMany
        private List<FlashCard> flashCards;

        User(String user, String pass, String passwordConfirm){
            this.userName = user;
            this.password = pass;
            this.passwordConfirm = passwordConfirm;
        }

        void appendCard(FlashCard card){
            flashCards.add(card);
        }
    }

UserServiceImpl.java


    package com.flashcards.flashcard;


    public class UserServiceImpl implements UserService{
        public User getUser(String name, String p){}
        public void updateUser(){}
        public void deleteUser(){}
    }

LoadDatabase.java, 为 Web 应用程序初始化数据。


    package com.flashcards.flashcard;

    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.boot.CommandLineRunner;
    import org.springframework.stereotype.Component;

    @Component
    public class LoadDatabase implements CommandLineRunner {


        private final FlashCardRepository flashcardRepository;
        private final UserRepository userRepository;

        @Autowired
        public LoadDatabase(FlashCardRepository flashcardRepository, UserRepository userRepository) {
            this.flashcardRepository = flashcardRepository;
            this.userRepository = userRepository;
        }

        @Override
        public void run(String... strings) throws Exception {

            this.userRepository.save(new User("user", "password", "password"));

        }
    }



【问题讨论】:

标签: spring hibernate spring-boot spring-security


【解决方案1】:

您可以使用configure(HttpSecurity http) 来保护您的端点。考虑到您有一些端点,如下所示。

/admin/newuser --> endPoint which can be access only by user with ROLE_ADMIN
/admin/users --> endPoint which can be access only by user with ROLE_ADMIN
/user/profile --> endPoint which can be access by user with ROLE_USER, ROLE_ADMIN

为此,您必须在模型中添加角色字段,该字段以ROLE_ADMIN、ROLE_USER 的形式保存在数据库中(ROLE_ROLETYPE 在保存到数据库时避免使用小写字母以避免进一步的错误)。您可以在configure() 中添加如下。

.antMatchers("/admin/**").hasRole("ADMIN")
.antMatchers("/user/**").hasAnyRole("ADMIN","USER") 

@Override
    protected void configure(HttpSecurity http) throws Exception{

         http
         .csrf().disable()
         .authorizeRequests()
         .antMatchers("/login","/logout").permitAll()
         .antMatchers("/admin/**").hasRole("ADMIN")
         .antMatchers("/user/**").hasAnyRole("ADMIN","USER")
         .anyRequest().authenticated()
         .and()
         .formLogin()
         .loginPage("/login")
         .loginProcessingUrl("/login");      
    }

如果您不想在 .antMatchers() 中设置的端点以外的端点对用户进行身份验证,则可以将 .anyRequest().authenticated() 更改为 .anyRequest().permitAll()

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-11-22
    • 2018-08-29
    • 2023-03-19
    • 1970-01-01
    • 1970-01-01
    • 2017-10-01
    • 2021-01-21
    • 2019-05-29
    相关资源
    最近更新 更多