在春季启动时使用cookie进行身份验

问题描述 投票:1回答:2

//我的Controller类的一部分

@RequestMapping("/login")
    public String login(HttpServletRequest request,HttpServletResponse response) {
        request.setAttribute("mode", "MODE_LOGIN");


        return "welcomepage";
    }

    @RequestMapping ("/login-user")
    public String loginUser(@ModelAttribute User user, HttpServletRequest request,HttpServletResponse response) {
        if((userService.findByUsernameAndPassword(user.getUsername(), user.getPassword())!=null)) {
            Cookie loginCookie=new Cookie("mouni","user.getUsername()");
            loginCookie.setMaxAge(30*5);
            response.addCookie(loginCookie);
        return "homepage";
        }
        else {
            request.setAttribute("error", "Invalid Username or Password");
            request.setAttribute("mode", "MODE_LOGIN");
            return "welcomepage";

        }

    }

我正在做一个关于java spring boot的库管理项目。我有一个问题,我想使用cookie进行身份验证。简而言之,在用户使用其凭据登录后,用户名应保存为cookie值。下次用户登录时,他只需输入用户名即可成功登录。请有人帮帮我

java spring-boot session-cookies
2个回答
1
投票

由于安全性是一个复杂的问题,我建议使用Spring Security,即使你的任务是没有。为了说明安全性的复杂性,我已经可以告诉您,您当前的代码存在漏洞,因为您信任明文用户名密码作为您的唯一身份验证。另一方面,Spring Security使用一个密钥来生成一个记住我的cookie,这样模仿某人就更加困难(除非你知道密钥)。

所以,如果您要使用Spring Security,首先需要创建一个UserDetailsService,它有一个名为loadByUsername()的方法。要实现这一点,您可以使用UserService并使用User构建器来构造Spring Security用户对象:

public class MyUserDetailsService implements UserDetailsService {
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        if ("admin".equalsIgnoreCase(username)) {
        return User.builder()
            .username(username)
            // This should contain the hashed password for the requested user
            .password("$2a$10$T5viXrOTIkraRe2mZPyZH.MAqKaR6x38L.rbmRp53yQ8R/cFrJkda")
            // If you don't need roles, just provide a default one, eg. "USER"
            .roles("USER", "ADMIN")
            .build();
    } else {
        // Throw this exception if the user was not found
        throw new UsernameNotFoundException("User not found");
    }
}

请注意,与您原来的UserService.findByUsernameAndPassword()相反,您不必自己检查密码,只需检索用户对象并传递散列密码即可。

下一步是提供适当的PasswordEncoder豆。在我的例子中,我使用BCrypt进行了10次旋转,所以我创建了以下bean:

@EnableWebSecurity
@Configuration
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    @Bean
    public PasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder(10);
    }

    @Bean
    public UserDetailsService userDetailsService() {
        return new MyUserDetailsService();
    }
}

下一步是配置Spring Security。例如:

@Override
protected void configure(HttpSecurity http) throws Exception {
    http
        .antMatcher("/**")
        .authorizeRequests()
            .anyRequest().authenticated()
            .and()
        .formLogin()
            .loginPage("/login.html").permitAll()
            .loginProcessingUrl("/login-user").permitAll().usernameParameter("username").passwordParameter("password")
            .defaultSuccessUrl("/welcome.html")
            .and()
        .rememberMe()
            .alwaysRemember(true)
            .tokenValiditySeconds(30*5)
            .rememberMeCookieName("mouni")
            .key("somesecret")
            .and()
        .csrf().disable();
}

在这种情况下,所有端点(/**)都将受到保护,您将在login.html上有一个包含两个表单字段(usernamepassword)的登录表单。表单的目标应为/login-user,当用户成功登录时,他将被重定向到/welcome.html

与您在代码中编写的内容类似,这将生成一个名为mouni的cookie,其中包含一个值(不再是普通用户名),它将在150秒内有效,就像您的示例中一样。

我在这里禁用CSRF,因为我使用的是简单的HTML表单,否则我必须添加一个模板引擎来传递CSRF密钥。理想情况下,您应该启用此功能。


0
投票

您正在使用Spring框架,它具有您尝试实现的相同功能。那为什么要手动呢?

看看春天的安全性。

https://docs.spring.io/spring-security/site/docs/current/reference/htmlsingle/

© www.soinside.com 2019 - 2024. All rights reserved.