SpringSecurity⾃定义⽤户登录
根据上⼀节的配置,默认在服务开启的时候会被要求⾃动的进⾏表单登陆。⽤到的⽤户名只能是⼀个固定的⽤户名ur,它的密码是每次启动的时候服务器⾃动⽣成的。最常见的场景是我们的⽤户是从数据库中获取的。
1.处理⽤户信息获取逻辑
import org.slf4j.LoggerFactory;
import org.authority.AuthorityUtils;
import org.urdetails.Ur;
import org.urdetails.UrDetails;
import org.urdetails.UrDetailsService;
import org.urdetails.UrnameNotFoundException;
import org.springframework.stereotype.Component;
import java.util.logging.Logger;
//⾃定义⽤户处理的逻辑
//⽤户的信息的rvice
@Component
public class MyUrDetailService implements UrDetailsService {
/**
* ⽇志处理类
*/
private org.slf4j.Logger logger = Class());
/**
* 根据⽤户名加载⽤户信息
*
* @param urname ⽤户名
* @return UrDetails
* @throws UrnameNotFoundException
*/
@Override
public UrDetails loadUrByUrname(String urname) throws UrnameNotFoundException {
logger.info("表单登录⽤户名:" + urname);
System.out.println("表单登录⽤户名:" + urname);
return new Ur(urname,"123456",true,
true,
true,
true,
}
}
这⾥我们⽤的curity⾥⾯的Ur进⾏存放,但是我们这边存放的密码是明⽂"123456",接下来会报错(没有⽤它的加密):
需要注意的是 在这⾥⽤了Spring默认的⼀个类Ur,在⾃⼰的实现过程中并不⼀定要⽤Spring的类
可以⾃⼰定义⼀个对象实现UrDetail接⼝。
public class Ur implements UrDetails,CredentialsContrain{}
2.加密⽤户的登录
注意在注⼊PasswordEncoder之前我们要在继承了WebSecurityConfigurerAdapter的类中注⼊并产⽣PasswordEncoder接⼝的实现类:
@Configuration
public class SecurityConfiguration extends WebSecurityConfigurerAdapter {
@Bean
public PasswordEncoder passwordEncoder(){
return new BCryptPasswordEncoder();
}
........这⾥是省略掉之前覆写了的⽅法
}
我们来修改下MyUrDetailService,如下:
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.GrantedAuthority;
import org.authority.AuthorityUtils;
import org.urdetails.Ur;
import org.urdetails.UrDetails;
import org.urdetails.UrDetailsService;
import org.urdetails.UrnameNotFoundException;
import org.pto.password.PasswordEncoder;
import org.springframework.stereotype.Component;
import java.util.ArrayList;
import java.util.List;
import java.util.logging.Logger;
//⾃定义⽤户处理的逻辑
//⽤户的信息的rvice
@Component
public class MyUrDetailService implements UrDetailsService {
loan/**
* ⽇志处理类
*/
private org.slf4j.Logger logger = Class());
@Autowired
private PasswordEncoder passwordEncoder;
/
**
拆除英语* 根据⽤户名加载⽤户信息
*
* @param urname ⽤户名
* @return UrDetails
* @throws UrnameNotFoundException
*/
@Override
public UrDetails loadUrByUrname(String urname) throws UrnameNotFoundException {
logger.info("表单登录⽤户名:" + urname);
System.out.println("表单登录⽤户名:" + urname);
List<GrantedAuthority> grantedAuthorityList = new ArrayList<>();
grantedAuthorityList.add(new GrantedAuthority() {
@Override
tp是什么意思
public String getAuthority() {
return "admin";
}
});
String pWord =de("123");
System.out.println("表单登录密码:" + pWord);
logger.info(pWord);
return new Ur("test",pWord,true,
true,
true,
true,
}
}
启动 使⽤test:123 即可登录成功
3.放⼊⾃定义Ur对象
MyUr:
package urity.demo.support;
import org.CredentialsContainer;
import org.GrantedAuthority;
import org.SpringSecurityCoreVersion;
import org.authority.AuthorityUtils;
import org.authority.SimpleGrantedAuthority;
import org.urdetails.Ur;
import org.urdetails.UrDetails;
import org.springframework.util.Asrt;
import java.io.Serializable;
import java.util.*;
@Slf4j
public class MyUr implements UrDetails, CredentialsContainer {
private static final long rialVersionUID = SpringSecurityCoreVersion.SERIAL_VERSION_UID;
// ~ Instance fields
// ================================================================================================ private String password;
private String urname;
private final Set<GrantedAuthority> authorities;
private final boolean accountNonExpired;
private final boolean accountNonLocked;
private final boolean credentialsNonExpired;
private final boolean enabled;
// ~ Constructors
// =================================================================================================== /**
* Calls the more complex constructor with all boolean arguments t to {@code true}.
*/
public MyUr(String urname, String password,
Collection<? extends GrantedAuthority> authorities) {
this(urname, password, true, true, true, true, authorities);
}
/**
* Construct the <code>Ur</code> with the details required by
* {@link org.springframework.curity.authentication.dao.DaoAuthenticationProvider}.
*
* @param urname the urname prented to the
* <code>DaoAuthenticationProvider</code>
* @param password the password that should be prented to the
* <code>DaoAuthenticationProvider</code>
* @param enabled t to <code>true</code> if the ur is enabled
* @param accountNonExpired t to <code>true</code> if the account has not expired
* @param credentialsNonExpired t to <code>true</code> if the credentials have not
* expired
* @param accountNonLocked t to <code>true</code> if the account is not locked
* @param authorities the authorities that should be granted to the caller if they
* prented the correct urname and password and the ur is enabled. Not null.
*
* @throws IllegalArgumentException if a <code>null</code> value was pasd either as
* a parameter or as an element in the <code>GrantedAuthority</code> collection
*/
public MyUr(String urname, String password, boolean enabled,
boolean accountNonExpired, boolean credentialsNonExpired,
boolean accountNonLocked, Collection<? extends GrantedAuthority> authorities) {
if (((urname == null) || "".equals(urname)) || (password == null)) {
throw new IllegalArgumentException(
"Cannot pass null or empty values to constructor");
}
this.urname = urname;
this.password = password;
this.accountNonExpired = accountNonExpired;
this.accountNonLocked = accountNonLocked;
this.authorities = Collections.unmodifiableSet(sortAuthorities(authorities));
}
public void tMyUrDetails(ity.Ur ur){
this.urname = ur.getUrname();
this.password = ur.getPassword();
}
// ~ Methods
// ======================================================================================================== public Collection<GrantedAuthority> getAuthorities() {
return authorities;
如何提高自己的语言表达能力}
public String getPassword() {
同义词典return password;
}
public String getUrname() {
return urname;
}
public boolean isEnabled() {
return enabled;
}
public boolean isAccountNonExpired() {
return accountNonExpired;
}
public boolean isAccountNonLocked() {
return accountNonLocked;
}
public boolean isCredentialsNonExpired() {
return credentialsNonExpired;
}
public void eraCredentials() {
password = null;
}
private static SortedSet<GrantedAuthority> sortAuthorities(
Collection<? extends GrantedAuthority> authorities) {
// Ensure array iteration order is predictable (as per
// Authorities() contract and SEC-717)
SortedSet<GrantedAuthority> sortedAuthorities = new TreeSet<GrantedAuthority>(
new MyUr.AuthorityComparator());
for (GrantedAuthority grantedAuthority : authorities) {
"GrantedAuthority list cannot contain any null elements");
sortedAuthorities.add(grantedAuthority);
}
}
private static class AuthorityComparator implements Comparator<GrantedAuthority>,
Serializable {
private static final long rialVersionUID = SpringSecurityCoreVersion.SERIAL_VERSION_UID; public int compare(GrantedAuthority g1, GrantedAuthority g2) {
// Neither should ever be null as each entry is checked before adding it to
// the t.
// If the authority is null, it is a custom authority and should precede
// others.
if (g2.getAuthority() == null) {
return -1;
}
if (g1.getAuthority() == null) {
return 1;
}
Authority().Authority());
}
}
/**
* Returns {@code true} if the supplied object is a {@code Ur} instance with the
* same {@code urname} value.
* <p>
* In other words, the objects are equal if they have the same urname, reprenting
* the same principal.
*/
@Override
you light up my lifepublic boolean equals(Object rhs) {
if (rhs instanceof MyUr) {
return urname.equals(((MyUr) rhs).urname);
}
return fal;
}
/**
* Returns the hashcode of the {@code urname}.
*/
@Override
public int hashCode() {
摄影培训学习return urname.hashCode();
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.String()).append(": ");
sb.append("Urname: ").append(this.urname).append("; ");
sb.append("Password: [PROTECTED]; ");
sb.append("Enabled: ").abled).append("; ");
sb.append("AccountNonExpired: ").append(this.accountNonExpired).append("; ");
sb.append("credentialsNonExpired: ").dentialsNonExpired)
.append("; ");
sb.append("AccountNonLocked: ").append(this.accountNonLocked).append("; ");
if (!authorities.isEmpty()) {
sb.append("Granted Authorities: ");
boolean first = true;搭配 英文
for (GrantedAuthority auth : authorities) {
if (!first) {
sb.append(",");
}
first = fal;
sb.append(auth);
}
}
el {
sb.append("Not granted any authorities");
}
String();
}
public static MyUr.UrBuilder withUrname(String urname) {
return new MyUr.UrBuilder().urname(urname);
}
/**
* Builds the ur to be added. At minimum the urname, password, and authorities
* should provided. The remaining attributes have reasonable defaults.
describe是什么意思*/
public static class UrBuilder {
private String urname;
private List<GrantedAuthority> authorities;
private boolean accountExpired;
private boolean accountLocked;
private boolean credentialsExpired;
private boolean disabled;
/**
* Creates a new instance
*/
private UrBuilder() {
}
/**
* Populates the urname. This attribute is required.
*
* @param urname the urname. Cannot be null.
* @return the {@link Ur.UrBuilder} for method chaining (i.e. to populate * additional attributes for this ur)
*/
private MyUr.UrBuilder urname(String urname) {
this.urname = urname;
return this;
}
/**
* Populates the password. This attribute is required.
*
* @param password the password. Cannot be null.
* @return the {@link Ur.UrBuilder} for method chaining (i.e. to populate * additional attributes for this ur)
*/
public MyUr.UrBuilder password(String password) {
this.password = password;
return this;
}
/**
* Populates the roles. This method is a shortcut for calling
* {@link #)}, but automatically prefixes each entry with
* "ROLE_". This means the following:
*
* <code>
* les("USER","ADMIN");
* </code>
*
* is equivalent to
*
* <code>
* builder.authorities("ROLE_USER","ROLE_ADMIN");
* </code>
英语四六级成绩查询时间*
* <p>
* This attribute is required, but can also be populated with
* {@link #)}.
* </p>
*
* @param roles the roles for this ur (i.e. USER, ADMIN, etc). Cannot be null, * contain null values or start with "ROLE_"
* @return the {@link Ur.UrBuilder} for method chaining (i.e. to populate * additional attributes for this ur)
*/
public MyUr.UrBuilder roles) {
List<GrantedAuthority> authorities = new ArrayList<GrantedAuthority>(
roles.length);
for (String role : roles) {
Asrt.isTrue(!role.startsWith("ROLE_"), role
+ " cannot start with ROLE_ (it is automatically added)");
authorities.add(new SimpleGrantedAuthority("ROLE_" + role));
}
return authorities(authorities);
}
/**
* Populates the authorities. This attribute is required.
*
* @param authorities the authorities for this ur. Cannot be null, or contain * null values
* @return the {@link Ur.UrBuilder} for method chaining (i.e. to populate * additional attributes for this ur)
* @e #)
*/
public MyUr.UrBuilder authorities) {
return authorities(Arrays.asList(authorities));
}
/**