我使用Spring安全授权来保护用户使用以下代码登录我的应用程序:
<jdbc-user-service data-source-ref="dataSource" users-by-username-query="SELECT username, password as password,1 as enabled FROM users WHERE username=?" authorities-by-username-query="SELECT username, authority,1 as enabled FROM users WHERE username =?" />
有没有办法在此查询中添加其他字段ex:ID,Email ...?
答案 0 :(得分:1)
如果要从数据库加载完整的自定义用户对象,然后在SecurityContextHolder
/ Session
中设置它,更好的方法是使用自定义UserDetailService
首先根据数据库表
创建一个简单的自定义用户实体@Entity
@Table(name = "users")
public class SecurityUser implements Serializable{
/**
*
*/
private static final long serialVersionUID = 1L;
@Id
@Column(name = "username", nullable = false, unique = true)
private String username;
@Column(name = "password", nullable = false)
@NotNull
private String password;
@Column(name = "type", nullable = false)
@NotNull
private String type;
@Column(name = "full_name", nullable = false)
@NotNull
private String fullName;
@Column(name = "email", nullable = false)
@NotNull
private String email;
//Gettters & Setters plus Default constructor
}
@Repository
public interface UserRepository extends JpaRepository<SecurityUser, Long> {
SecurityUser findByUsername(String username);
}
User
public class CurrentUser extends User {
/**
*
*/
private static final long serialVersionUID = 1L;
private SecurityUser securityUser;
public CurrentUser(SecurityUser securityUser) {
super(securityUser.getUsername(), securityUser.getPassword(), AuthorityUtils.createAuthorityList(securityUser.getRole().toString()));
this.securityUser = securityUser;
}
public SecurityUser getSecurityUser() {
return securityUser;
}
public String getRole() {
return securityUser.getRole();
}
}
@Service
public class CurrentUserDetailsService implements UserDetailsService {
@Autowired
private UserRepository userService;
@Autowired
public CurrentUserDetailsService(UserRepository userService) {
this.userService = userService;
}
public CurrentUserDetailsService() {
}
@Override
public CurrentUser loadUserByUsername(String username) throws UsernameNotFoundException, DataAccessException {
SecurityUser user = userService.findByUsername(username);
return new CurrentUser(user);
}
}
当您使用基于XML的配置时,请在配置文件中执行以下操作:
<bean id="myUserDetailsService"
class="complete-path-to-serviceClasss.MyUserDetailsService"/>
<security:authentication-manager>
<security:authentication-provider
user-service-ref="myUserDetailsService" >
<security:password-encoder ref="passwordEncoder">
</security:password-encoder>
</security:authentication-provider>
</security:authentication-manager>
现在在任何地方,如果您在用户登录时执行以下行,它将为您提供包含所有数据的CurrentUser
对象
CurrentUser user = SecurityContextHolder.getContext().getAuthentication().getPrincipal()
答案 1 :(得分:0)
这仅用于身份验证,在用户登录后,您可以像这样检查登录用户:
@RequestMapping(path="loggedInUser", method={RequestMethod.GET}, produces={MediaType.APPLICATION_JSON_UTF8_VALUE})
@ResponseBody
public User getLoggedInUser(Principal principal) throws SQLException{
return database.getUser(principal.getName());
}
或者您只需返回principal.getName()