首页 / JAVA / Shiro-java环境配置使用
Shiro-java环境配置使用
内容导读
互联网集市收集整理的这篇技术教程文章主要介绍了Shiro-java环境配置使用,小编现在分享给大家,供广大互联网技能从业者学习和参考。文章包含7772字,纯文字阅读大概需要12分钟。
内容图文
1.自定义Realm使用完成验证
1.1自定义realm类:继承AuthorizingRealm,实现其验证和授权方法
package com.gavin.realm;
import java.util.List;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import com.dqpi.service.UserService;
import com.gavin.model.User;
public class CustomRealm extends AuthorizingRealm {
//设置realm的名称
@Override
public void setName(String name) {
// TODO Auto-generated method stub
super.setName("CustomRealm");
}
//用于授权
@Override
protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection arg0) {
// TODO Auto-generated method stub
return null;
}
//用于认证
@Override
protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
// TODO Auto-generated method stub
//1.从token中取出用户的身份信息
//方式一
String userName = (String) token.getPrincipal();
String password = new String((char [])token.getCredentials());
//方式二
// UsernamePasswordToken usernamePasswordToken= (UsernamePasswordToken) token;
// String userName = (String) usernamePasswordToken.getUsername();//用户名
// String password = new String(usernamePasswordToken.getPassword());//密码
//2.根据用户的账号从数据库中查询
System.out.println("从数据库中查询“"+userName+"“的信息");
UserService userService = new UserService();
//调用login方法获得查询获得的集合
List<User> users = userService.login(userName);
//3.如果查询不到抛出账户不存在异常
if(users.isEmpty()) {
throw new UnknownAccountException();
}
//4.如果查询到进行判断是否可以完成登录
else {
String userPassword = users.get(0).getPassword();
System.out.println(password);
//如果密码正确,返回验证信息AuthenticationInfo
if(userPassword.equals(password)) {
SimpleAuthenticationInfo simpleAuthenticationInfo = new SimpleAuthenticationInfo(userName, password, this.getName());
return simpleAuthenticationInfo;
}
//如果密码不正确抛出验证信息异常
else {
throw new IncorrectCredentialsException();
}
}
}
}
注:这里使用的UserService在下面给出,使用的是hibernate框架
package com.dqpi.service;
import java.util.List;
import com.gavin.dao.UserDao;
import com.gavin.daoimp.UserDaoImp;
import com.gavin.model.User;
public class UserService {
UserDao userDao = new UserDaoImp();
public List<User> login(String name){
return userDao.login(name);
}
}
package com.gavin.daoimp;
import java.util.ArrayList;
import java.util.List;
import org.hibernate.Query;
import org.hibernate.Session;
import com.dqpi.util.HibernateUtil;
import com.gavin.dao.UserDao;
import com.gavin.model.User;
public class UserDaoImp implements UserDao {
@Override
public List<User> login(String name) {
List <User> userList = new ArrayList<User>();
Session session = HibernateUtil.getSessionFactory().getCurrentSession();
session.beginTransaction();
Query query = session.createQuery("from User c where c.name='"+name+"'");
userList = (List <User>)query.list();
session.getTransaction().commit();
HibernateUtil.getSessionFactory().close();
return userList;
}
}
1.2在配置文件中注入realm
[main]
#自定义realm
CustomRealm=com.gavin.realm.CustomRealm
#配置到securityManager中,相当于spring中的注入
securityManager.realms=$CustomRealm
1.3hibernate的配置文件
<?xml version='1.0' encoding='utf-8'?>
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD 3.0//EN"
"http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
<session-factory>
<!-- Database connection settings -->
<property name="connection.driver_class">com.mysql.cj.jdbc.Driver</property>
<property name="connection.url">jdbc:mysql://localhost:3306/Shiro_Realm?serverTimezone=UTC</property>
<property name="connection.username">root</property>
<property name="connection.password">123456</property>
<!-- JDBC connection pool (use the built-in) -->
<property name="connection.pool_size">1</property>
<!-- SQL dialect -->
<property name="dialect">org.hibernate.dialect.MySQLDialect</property>
<!-- Enable Hibernate's automatic session context management -->
<property name="current_session_context_class">thread</property>
<!-- Disable the second-level cache -->
<property name="cache.provider_class">org.hibernate.cache.internal.NoCacheProvider</property>
<!-- Echo all executed SQL to stdout -->
<property name="show_sql">true</property>
<property name="format_sql">true</property>
<!-- Drop and re-create the database schema on startup -->
<property name="hbm2ddl.auto">update</property>
<mapping class="com.gavin.model.User"/>
<!--指向我们的model -->
</session-factory>
</hibernate-configuration>
注:使用的是mysql的数据库,可以自己更改连接信息
1.4Hibernate的工具类
package com.dqpi.util;
import java.text.Annotation;
import org.hibernate.SessionFactory;
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
import org.hibernate.cfg.AnnotationConfiguration;
import org.hibernate.cfg.Configuration;
import org.hibernate.service.ServiceRegistry;
public class HibernateUtil
{
private static final SessionFactory sessionFactory;
static
{
try
{
Configuration cfg = new Configuration().configure();
ServiceRegistry serviceRegistry = new StandardServiceRegistryBuilder().applySettings(cfg.getProperties()).build();
sessionFactory = cfg.buildSessionFactory(serviceRegistry);
}
catch (Throwable e)
{
throw new ExceptionInInitializerError(e);
}
}
public static SessionFactory getSessionFactory()
{
return sessionFactory;
}
}
1.5Model层
package com.gavin.model;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
@Entity
public class User {
private int id;
private String name;//用户名 主键
private String password;//密码
private String manager;//权限
@GeneratedValue
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getManager() {
return manager;
}
public void setManager(String manager) {
this.manager = manager;
}
@Id
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
@Override
public String toString() {
return "User [name=" + name + ", password=" + password + ", manager=" + manager + "]";
}
}
1.6测试方法
public static void main(String[] args) {
if(login("lisi","123")){
System.out.println("登录成功!");
}
}
public static Boolean login(String username,String password){
//准备
//获取SecurityManager工厂,试用Ini配置文件初始化SecurityManager
Factory<SecurityManager> factory = new IniSecurityManagerFactory("classpath:realm.ini");
//得到SecurityManager的实例,并绑定给SecurityUtils
SecurityManager securityManager = factory.getInstance();
SecurityUtils.setSecurityManager(securityManager);
//得到Subject及创建用户/密码身份验证Token(即用户身份/凭证)
Subject currentUser = SecurityUtils.getSubject();
UsernamePasswordToken token = new UsernamePasswordToken(username,password);
try {
currentUser.login(token);
return true;
}
catch ( UnknownAccountException uae ) {
System.out.println("账户或密码错误");
}
catch ( IncorrectCredentialsException ice ) {
System.out.println("账户或密码错误");
}
catch ( LockedAccountException lae ) {
System.out.println("账号被锁定,请联系管理员");
}
catch ( ExcessiveAttemptsException eae ) {
System.out.println("错误次数过多,请稍后再试");
}
catch ( AuthenticationException ae ) {
System.out.println("登录失败");
}
//登出
currentUser.logout();
return false;
}
注意:在测试方法中捕获异常,并打印相应的错误信息。
最后上源码地址:
链接: https://pan.baidu.com/s/1a3T5LXMrP7up-5oS5LZKiA
提取码: j7rs
内容总结
以上是互联网集市为您收集整理的Shiro-java环境配置使用全部内容,希望文章能够帮你解决Shiro-java环境配置使用所遇到的程序开发问题。 如果觉得互联网集市技术教程内容还不错,欢迎将互联网集市网站推荐给程序员好友。
内容备注
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 gblab@vip.qq.com 举报,一经查实,本站将立刻删除。
内容手机端
扫描二维码推送至手机访问。