首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >弹簧的UserDetailsService

弹簧的UserDetailsService
EN

Stack Overflow用户
提问于 2016-10-29 16:16:05
回答 1查看 690关注 0票数 1

我试图在我的Spring应用程序中配置Security,以便只允许某些用户访问特定的URL,如果他们有特定的角色,即我在创建用户时存储的用户或管理角色。我看了几个例子,这里做了我想要做的事情。我有点困惑于Spring的UserDetailsService接口,以及当我试图访问像localhost:8080/addtour这样的URL时,应该如何将用户名从我的用户传递给UserDetailsService。目前,我的代码如下所示:

代码语言:javascript
复制
@Data
@Scope("session")
public class User {

    @Id
    private String id;
    private String userName;
    private String password;
    private List<Role> roles;

我的SecurityConfig课程:

代码语言:javascript
复制
@Configuration 
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {

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

        http
        .formLogin()
            .loginPage("/login")
            .permitAll()
            .and()
        .exceptionHandling()
            .accessDeniedPage("/accessdenied")
            .and()
        .authorizeRequests()
            .antMatchers("/resources/**", "/signup", "/search").permitAll()
            .antMatchers("/viewtour").hasAnyRole("USER", "ADMIN")
            .antMatchers("/addtour").hasAnyRole("ADMIN")
            .and()
        .logout()
            .permitAll()
            .logoutSuccessUrl("/index.html");
    }

    @Override  
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {  
        auth.userDetailsService(new UserDetailServiceImpl());  
    }

实现SpringUserDetailServiceUserDetailServiceImpl

代码语言:javascript
复制
public class UserDetailServiceImpl implements UserDetailsService {

    @Autowired
    private UserService userService;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        try {  
            User user = userService.retrieveUserByUserName(username);  
            if (user == null) {  
                return null;  
            }  
            return new org.springframework.security.core.userdetails.User(user.getUserName(), user.getPassword(), getAuthorities(user));  
        } catch (Exception e){  
            throw new UsernameNotFoundException("User not found");  
        }  
    }  

    private Set<GrantedAuthority> getAuthorities(User user){  
        Set<GrantedAuthority> authorities = new HashSet<GrantedAuthority>();  
        for (Role role : user.getRoles()) {  
            GrantedAuthority grantedAuthority = new SimpleGrantedAuthority(role.toString());  
            authorities.add(grantedAuthority);  
        }  
        System.out.println("user authorities are " + authorities.toString());  
        return authorities;  
    }

我的登录页面使用Thymeleaf:

代码语言:javascript
复制
<!DOCTYPE html SYSTEM "http://www.thymeleaf.org/dtd/xhtml1-strict-thymeleaf-spring4-4.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xmlns:th="http://www.thymeleaf.org">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<link rel="stylesheet" type="text/css" href="css/style.css"/>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" />
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap-theme.min.css" />

</head>
<body>
	<div>
		<div class="content">
			<form action="#" th:action="@{/login}" th:object="${user}" method="post">
				<div class="panel panel-default">
					<br />
					<h1 class="panel-title header-tab">
						Login or <a href="/signup.html">Sign Up Here</a>
					</h1>
					<br />
					<div class="panel-body">
						<div class="form-group">
							<label for="inputEmail" class="control-label col-xs-5">Username
								or Email</label>
							<div class="col-xs-7">
								<input type="text" class="form-control" id="inputUsername" th:field="*{userName}" placeholder="Username or Email" />
							</div>
						</div>
						<br/><br/>
						<div class="form-group">
							<label for="inputPassword" class="control-label col-xs-5">Password</label>
							<div class="col-xs-7">
								<input type="password" class="form-control" id="inputPassword" th:field="*{password}" placeholder="Password" />
							</div>
						</div>
						<div class="form-group">
							<div class="col-xs-offset-5 col-xs-10">
								<div class="checkbox">
									<label><input type="checkbox" />Remember Me</label>
								</div>
							</div>
						</div>
						<div class="form-group">
							<div class="col-xs-offset-5 col-xs-7 btn-lg">
								<input type="submit" value="Sign In" class="btn btn-primary btn-block"/>
							</div>
						</div>
					</div>
				</div>
			</form>
		</div>
	</div>
</body>
</html>

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2016-10-30 19:21:53

登录页面中的参数名称是错误的,请参见

  • FormLoginConfigurer#usernameParameter: 在执行身份验证时查找用户名的HTTP参数。默认情况下是“用户名”。
  • FormLoginConfigurer#passwordParameter: 在执行身份验证时查找密码的HTTP参数。默认为“密码”。

更改登录页面中参数的名称或更改SecurityConfig中的名称。

票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/40321085

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档