如何使用Spring Boot对用户进行身份验证?

时间:2019-07-12 23:22:22

标签: spring hibernate spring-boot spring-security

我已经设置了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"));

        }
    }



1 个答案:

答案 0 :(得分: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()