This is the 9th day of my participation in the August More Text Challenge
Integrated springboot
The premise
Create A page to differentiate user permissions (user A can only go to add, not update)
1. Create a new project and import web and Thymeleaf
2. Write your home PAGE HTML and put it in the Templates directory!
3. Write the Add,update page and put it in the templates/user directory
4. Write controller jump to home page, add, update
Formal (template)
1. Import the Shro-Spring integration package
<! -- https://mvnrepository.com/artifact/org.apache.shiro/shiro-spring --> <dependency> <groupId>org.apache.shiro</groupId> < artifactId > shiro - spring < / artifactId > < version > 1.5.3 < / version > < / dependency >Copy the code
2. Write configuration classes (basic framework),
Write a realm class first (custom required)
public class realm extends AuthorizingRealm {
/ / authorization
@Override
protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
System.out.println("Realm authentication -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- AuthorizationInfo");
return null;
}
/ / certification
@Override
protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throwsAuthenticationException {
System.out.println("Realm authorization -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- AuthenticationInfo");
return null; }}Copy the code
ShiroConfig: The order is realm, Manager, and ShiroFilterFactoryBean
@Configuration
public class shiroConfig {
// shiroFilterFactoryBan
@Bean
public ShiroFilterFactoryBean bean(@Qualifier("manager") DefaultWebSecurityManagerdefaultWebSecurityManager){
ShiroFilterFactoryBean bean = new ShiroFilterFactoryBean();
// Set the security manager
bean.setSecurityManager(defaultWebSecurityManager);
return bean;
}
/ / DefaultWebSecurityManager this is the second, because the manager need to realm
@Bean(name="manager")
public DefaultWebSecurityManager defaultWebSecurityManager(@Qualifier("realm") realmrealm){
DefaultWebSecurityManager defaultWebSecurityManager = newDefaultWebSecurityManager();
Realm () can't be configured directly to a realm (), because this realm is spring-managed, so use the spring container bean object for the method arguments
defaultWebSecurityManager.setRealm(realm);
return defaultWebSecurityManager;
}
// Realm object, need to customize (create a realm class) this is the first step first step
@Bean
public realm realm(a){
return newrealm(); }}Copy the code
3. Implement user rights
Inside the bean method
HashMap<String,String> map = new HashMap<>();
// Resources here are written to paths (in controller), not pages
map.put("/toadd"."authc");
map.put("/toupdate"."authc");
// Set the contents of the filter (which paths to filter and their access permissions)
bean.setFilterChainDefinitionMap(map);
// Redirects to the login page if blocked
bean.setLoginUrl("/tologin");
Copy the code
4. Write controller login operations
@RequestMapping("/login")
public String login(String username,String password,Model model){
// Get the current user
Subject subject = SecurityUtils.getSubject();
// Encapsulate user login data
UsernamePasswordToken token = new UsernamePasswordToken(username, password);
try{
// Execute the login process (shiro did all the verification steps for us), and raise an exception if there is an error
subject.login(token);
return "index";
}catch (UnknownAccountException e){
model.addAttribute("msg"."User does not exist");
return "/user/login";
}catch (IncorrectCredentialsException e){
model.addAttribute("msg"."Password error");
return "/user/login"; }}Copy the code
Login:
Then look at the console: find the method that executes realm
There is no connection between the two, but Shiro does it for us automatically, so we can add login data to realm
5. Realm writes data capture and authentication
/ / certification
@Override
protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throwsAuthenticationException {
System.out.println("Realm authentication -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- AuthenticationInfo");
// You can get data from the database. Set the data manually
String username="YY";
String pasword = "1";
UsernamePasswordToken usertoken = (UsernamePasswordToken)token;
// The token in the authentication parameter exists globally, and can be used here if the login side is sealed
if(! usertoken.getUsername().equals(username)){// return null throws an exception, indicating that the username does not exist
return null;
}
// We do not do password authentication, may leak. Shiro secretly does password authentication,
return new SimpleAuthenticationInfo("",pasword,"");
}
Copy the code
Exceptions will be detected during login
6. Set the authorization page
// Set the page bean.setunAuthorizedURL ("/tounauthorized") for the unauthorized request;Copy the code
Integration of mybatis
The first few operations are the same as springBoot integrating mybatis.
1. Add database operations in realm authentication
// Get data from the database
User user = userService.findUserByUsername(usertoken.getUsername());
// The token in the authentication parameter exists globally, and can be used here if the login side is sealed
if(user==null) {return null;
}
// We do not do password authentication, may leak. Shiro secretly does password authentication,
return new SimpleAuthenticationInfo("",user.getPassword(),"");
}
Copy the code
2. Add permissions for the current user
Realme authorization methods (two)
- Grant this permission to all users
- Obtain the permission of the user object through the database operation in authentication and give it to the current user
SQL > alter database field utf8_general_ci to UTf8_bin; if(! user.getLoginname().equals(token.getUsername())){ throw new AuthenticationException(); }
// Authorization, used to authorize an account
@Override
protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
// As long as you pass through here, you will be authorized
SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
// Grant this permission to each user
// info.addStringPermission("user:add");
// Get the current login user
Subject subject = SecurityUtils.getSubject();
// Get the user object from the first user password below
User user = (User)subject.getPrincipal();
// Set the privileges in the database user object for subject
info.addStringPermission(user.getPerms());
return info;
}
Copy the code
User login status:
map.put("/toadd","perms[user:add]");
map.put("/toupdate","perms[user:update]");
Copy the code
So when YY logs in, it can only access the Update page
When yzy logs in, no web pages can be accessed
When Y logs in, he can access the Add page