Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to connect database with Spring Boot+CAS single sign-on in Java

2025-02-24 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/02 Report--

This article introduces the relevant knowledge of "how to connect the database with Spring Boot+CAS single sign-on in Java". In the operation of actual cases, many people will encounter such a dilemma, so let the editor lead you to learn how to deal with these situations. I hope you can read it carefully and be able to achieve something!

1. Overall thinking

First, let's take a look at the overall thinking.

We use CAS Server to do single sign-on, CAS Server is mainly responsible for authentication, that is, it mainly solves the login problem. After the login is successful, there is another issue of permissions to be handled, and the issue of permissions is left to each CAS Client to handle, not in the CAS Server.

@ Primary

Public class UserDetailsServiceImpl implements UserDetailsService {

@ Override

Public UserDetails loadUserByUsername (String s) throws UsernameNotFoundException {

Return new User (s, "123", true, true

AuthorityUtils.createAuthorityList ("ROLE_user"))

}

}

When will this code be executed?

If we don't use CAS, this code is of course executed when the user logs in. When the user logs in, the user's information is queried from the database and then verified.

If we use CAS, the verification of user login will be performed on CAS Server, and CAS Client will not have to do the verification work, but why do we need to define UserDetailsService? This is to return to CAS Client with the user name after the user has successfully logged in on CAS Server, and then we go to the database to get the details of the user based on the user name, including the user's role, and then use the role in later authentication.

Okay, this is a general idea for us. Next, let's look at the concrete implementation.

two。 Concrete realization

2.1 preparation work

First of all, let's prepare the user table, role table, and user role association table in the database:

CREATE TABLE `t _ role` (

`id` bigint (20) NOT NULL AUTO_INCREMENT

`name` varchar (255) COLLATE utf8mb4_unicode_ci DEFAULT NULL

`name_ zh` varchar (255) COLLATE utf8mb4_unicode_ci DEFAULT NULL

PRIMARY KEY (`id`)

) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci

CREATE TABLE `t _ user` (

`id` bigint (20) NOT NULL AUTO_INCREMENT

`account_non_ credred` bit (1) NOT NULL

`account_non_ locked` bit (1) NOT NULL

`credentials_non_ credred` bit (1) NOT NULL

`enabled` bit (1) NOT NULL

`password` varchar (255) COLLATE utf8mb4_unicode_ci DEFAULT NULL

`username` varchar (255) COLLATE utf8mb4_unicode_ci DEFAULT NULL

PRIMARY KEY (`id`)

) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci

CREATE TABLE `troomuser _ roles` (

`troomuserid` bigint (20) NOT NULL

`roles_ id` bigint (20) NOT NULL

KEY `FKj47yp3htsoajht9793tbdrp4` (`FKj47yp3htsoajht9793d`)

KEY `FK7l00c7jb4804xlpmk1k26texy` (`troomuserid`)

CONSTRAINT `FK7l00c7jb4804xlpmk1k26texy` FOREIGN KEY (`troomuserid`) REFERENCES `tuser` (`id`)

CONSTRAINT `FKj47yp3htsoajht9793tbdrp4` FOREIGN KEY (`FKj47yp3htsoajht9793tbdrp4` FOREIGN KEY (`FKj47yp3htsoajht9793tbdrp4`) REFERENCES `t_ role` (`id`)

) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci

INSERT INTO `trole` (`id`, `name`, `role`) VALUES (1), (2) VALUES, (2) "ordinary user", (2)

INSERT INTO `t _ user` (`id`, `account_non_ locked`, `credentials_non_ locked`, `enabled`, `password`, `username`) VALUES.

INSERT INTO `tpromouserroles` (`troomuserid`, `roles_ id`) VALUES (1meme 1), (2mai 2)

2.2 CAS Server

Then we will add two dependencies to the pom.xml file of CAS Server:

Org.apereo.cas

Cas-server-support-jdbc-drivers

${cas.version}

Org.apereo.cas

Cas-server-support-jdbc

${cas.version}

Note that there is no need to add a database driver here, the system will solve it automatically.

After the addition is completed, before

Add the following configuration to the src/main/resources/application.properties file:

Cas.authn.jdbc.query [0] .url = jdbc:mysql://127.0.0.1:3306/withjpa?useUnicode=true&characterEncoding=UTF-8&autoReconnect=true&useSSL=false

Cas.authn.jdbc.query [0] .user = root

Cas.authn.jdbc.query [0] .password = 123

Cas.authn.jdbc.query [0] .SQL = select * from t_user where username=?

Cas.authn.jdbc.query [0] .fieldPassword = password

Cas.authn.jdbc.query [0] .driverClass = com.mysql.cj.jdbc.Driver

The first three lines of configuration are the basic database connection configuration, which I don't need to say.

The fourth line indicates that the user query sql is configured to query all the information of the user according to the user name.

The fifth line indicates what is the name of the password field in the database.

The sixth line is database-driven.

OK, after the configuration is complete, let's restart CAS Server:

. / build.sh run

After a successful startup, the browser enters

Https://cas.javaboy.org:8443/cas/login can go to the login page (note that it is https):

At this point, the login user name is javaboy and the password is 123.

2.3 CAS Client

Next, let's take a look at what CAS Client needs to improve.

The next configuration is the third scheme to achieve single sign-on in Spring Boot! It is completed on the basis of one article, so the friends who have not read the previous article suggest to take a look at it first.

At the same time, for the sake of simplicity of the case, I use JPA to manipulate the database here.

The main purpose of docking in CAS Client is to implement UserDetailsService interface. Database queries are used here, so let's first add database-related dependencies:

Mysql

Mysql-connector-java

Org.springframework.boot

Spring-boot-starter-data-jpa

Then configure the database connection information in application.properties:

Spring.datasource.username=root

Spring.datasource.password=123

Spring.datasource.url=jdbc:mysql:///withjpa?useUnicode=true&characterEncoding=UTF-8&serverTimezone=Asia/Shanghai

Spring.jpa.database=mysql

Spring.jpa.database-platform=mysql

Spring.jpa.hibernate.ddl-auto=update

Spring.jpa.show-sql=true

Spring.jpa.properties.hibernate.dialect=org.hibernate.dialect.MySQL8Dialect

They are all regular configurations, so we won't repeat them.

Next, we create two entity classes that represent the user role as the user class:

User roles:

@ Entity (name = "t_role")

Public class Role {

@ Id

@ GeneratedValue (strategy = GenerationType.IDENTITY)

Private Long id

Private String name

Private String nameZh

/ / omit getter/setter

}

This entity class is used to describe user role information, including role id and role name (English and Chinese). @ Entity indicates that this is an entity class. After the project is started, a role table will be automatically created in the database based on the attributes of the entity class.

User entity class:

@ Entity (name = "t_user")

Public class User implements UserDetails {

@ Id

@ GeneratedValue (strategy = GenerationType.IDENTITY)

Private Long id

Private String username

Private String password

Private boolean accountNonExpired

Private boolean accountNonLocked

Private boolean credentialsNonExpired

Private boolean enabled

@ ManyToMany (fetch = FetchType.EAGER,cascade = CascadeType.PERSIST)

Private List roles

@ Override

Public Collection

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report