当前位置:网站首页>Vert. x: A simple login access demo (simple use of router)
Vert. x: A simple login access demo (simple use of router)
2022-07-06 11:47:00 【You are little KS】
current version :jdk1.8
、vert.x 4.2.4
1. Statement
The current content is mainly for recording and learning Vert.x Implement a simple login access control operation demo, Current content reference : Official documents , This is a very simple and interesting project
The main function :
- Realize very simple login function
- It is very simple to realize the logout function
- Implement access control ( Only after logging in can you access )
- Implementation is based on Vert.x Of session Login control function ( Reference resources Official documents )
pom rely on
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<vertx.version>4.2.4</vertx.version>
</properties>
<dependencyManagement>
<dependencies>
<dependency>
<groupId>io.vertx</groupId>
<artifactId>vertx-stack-depchain</artifactId>
<version>${vertx.version}</version>
<type>pom</type>
<scope>import</scope>
</dependency>
</dependencies>
</dependencyManagement>
<dependencies>
<dependency>
<groupId>io.vertx</groupId>
<artifactId>vertx-web</artifactId>
</dependency>
</dependencies>
2. Custom login control demo
1. Main programming
import io.vertx.core.AbstractVerticle;
import io.vertx.core.MultiMap;
import io.vertx.core.Promise;
import io.vertx.core.http.HttpMethod;
import io.vertx.core.json.JsonObject;
import io.vertx.ext.auth.User;
import io.vertx.ext.web.Router;
public class MainVerticle extends AbstractVerticle {
boolean login = false;
@Override
public void start(Promise<Void> startPromise) throws Exception {
// Create a Router
Router router = Router.router(vertx);
// Login operation
router.route("/login").handler(context->{
MultiMap queryParams = context.queryParams();
String username = queryParams.get("username");
String password = queryParams.get("password");
User user = User.create(new JsonObject().put("username", username).put("password", password));
context.setUser(user);
login=true;
context.json( new JsonObject().put("status", 200).put("msg", "login success!"));
});
// All operations are allowed only after login verification ( Certified operating )
router.route().handler(context->{
User user = context.user();
System.out.println(user);
if(!login){
System.out.println(" Failed to authenticate user !");
context.json( new JsonObject().put("status", 500).put("msg", "no login"));
}else {
// Direct release executes the next router
context.next();
}
});
router.route("/logout").handler(context->{
login=false;
context.json( new JsonObject().put("status", 200).put("msg", "login out success!"));
});
// Perform the requested operation
router.route("/hello").method(HttpMethod.GET).handler(context->{
//context.json( new JsonObject().put("status", 200).put("msg", "ok"));
context.json(new JsonObject("{\"status\":200,\"msg\":\"ok\"}"));
});
// Create the HTTP server
vertx.createHttpServer()
.requestHandler(router)
.listen(8888)
.onSuccess(server ->
System.out.println(
"HTTP server started on port " + server.actualPort()
)
);
}
}
The most important one is context.next();
, Release means to let the next matching continue , Be careful login Of router Must be in front of full match login authentication , otherwise login It will also be blocked
, Here you can log in without a password , Watch out for interception router The question of order
2. The deployment process
public class Application {
public static void main(String[] args) {
Vertx vertx = Vertx.vertx();
// Deploy one directly vertx Program
vertx.deployVerticle(new MainVerticle());
}
}
3. Test custom login demo
1. Start the service program
Direct access to protected , Found as 500
Log in
Revisit /hello
Log out
Revisit /hello, Be intercepted again
Test success !
4. be based on Vert.x Of Session Login control of mechanism demo
This function mainly depends on Session Realization , It is better than the previous manual control
@Override
public void start(Promise<Void> startPromise) throws Exception {
// Create a Router
Router router = Router.router(vertx);
//bindLoginAndLogoutRouter(router);
router.route().handler(SessionHandler.create(LocalSessionStore.create(vertx)));
AuthenticationProvider authenticationProvider = new AuthenticationProvider() {
@Override
public void authenticate(JsonObject credentials, Handler<AsyncResult<User>> resultHandler) {
//String username = credentials.getString("username");
//String password = credentials.getString("password");
//System.out.println("username:"+username+",password="+password);
// An empty implementation
}
};
// Process login interface , Use form login
//router.post("/login").handler(FormLoginHandler.create(authenticationProvider));
// Set a static server to serve static resources, e.g. the login page
// Open login static page
//router.route().handler(StaticHandler.create());
// Start binding login routes
router.route("/login").handler(context->{
MultiMap queryParams = context.queryParams();
String username = queryParams.get("username");
String password = queryParams.get("password");
// The user name and password are admin Is allowed to login
if(username!=null&&password!=null&&"admin".equals(username.trim())&&"admin".equals(password.trim())) {
User user = User.create(new JsonObject().put("username", username).put("password", password));
context.setUser(user);
context.json( new JsonObject().put("status", 200).put("msg", "login success!"));
}else {
context.json( new JsonObject().put("status", 500).put("msg", "login failed!"));
}
});
router.route("/loginpage").handler(context->{
context.json( new JsonObject().put("status", 200).put("msg", "please login!"));
});
// Bind authentication route
// All operations are allowed only after login verification ( Certified operating )
RedirectAuthHandler authHandler = RedirectAuthHandler.create(authenticationProvider);
router.route().handler(authHandler);
// Bind logout route
router.route("/logout").handler(context->{
// Clear the logged in user operation
context.clearUser();
context.json( new JsonObject().put("status", 200).put("msg", "login out success!"));
});
// Perform the requested operation
router.route("/hello").method(HttpMethod.GET).handler(context->{
context.json(new JsonObject("{\"status\":200,\"msg\":\"ok\"}"));
});
// Create the HTTP server
vertx.createHttpServer()
// Handle every request using the router
.requestHandler(router)
// Start listening
.listen(8888)
// Print the port
.onSuccess(server ->
System.out.println(
"HTTP server started on port " + server.actualPort()
)
);
}
1.router.route().handler(SessionHandler.create(LocalSessionStore.create(vertx)));
Open for indication session Control storage mechanism
Only open Session And open the certification to provide , Then create User It will be saved in the server after successful login
2. context.setUser(user);
Indicates that the authentication object is set to the server based on session The way
3. context.clearUser();
Indicates deleting session Corresponding user
4. /loginpage Indicates the default login location , That is, the location of redirection after login failure
Test access /hello, Directly redirected to /loginpage Address
Wrong login
Correct login
You can visit at will after logging in
Log out
Found this after debugging : adopt cookie controlled
Test success !
边栏推荐
- What does usart1 mean
- How to configure flymcu (STM32 serial port download software) is shown in super detail
- 使用LinkedHashMap实现一个LRU算法的缓存
- Hutool中那些常用的工具类和方法
- vs2019 桌面程序快速入门
- [yarn] CDP cluster yarn configuration capacity scheduler batch allocation
- Library function -- (continuous update)
- 库函数--(持续更新)
- MySQL主从复制的原理以及实现
- Redis面试题
猜你喜欢
Pytorch基础
Machine learning -- census data analysis
FTP文件上传文件实现,定时扫描文件夹上传指定格式文件文件到服务器,C语言实现FTP文件上传详解及代码案例实现
Redis面试题
MTCNN人脸检测
AcWing 1298. Solution to Cao Chong's pig raising problem
Learning question 1:127.0.0.1 refused our visit
Kept VRRP script, preemptive delay, VIP unicast details
Linux yum安装MySQL
error C4996: ‘strcpy‘: This function or variable may be unsafe. Consider using strcpy_ s instead
随机推荐
[CDH] cdh5.16 configuring the setting of yarn task centralized allocation does not take effect
Are you monitored by the company for sending resumes and logging in to job search websites? Deeply convinced that the product of "behavior awareness system ba" has not been retrieved on the official w
搞笑漫画:程序员的逻辑
Composition des mots (sous - total)
牛客Novice月赛40
AI benchmark V5 ranking
Face recognition_ recognition
[Blue Bridge Cup 2017 preliminary] grid division
库函数--(持续更新)
AcWing 1298.曹冲养猪 题解
Reading BMP file with C language
快来走进JVM吧
Software testing and quality learning notes 3 -- white box testing
[Flink] cdh/cdp Flink on Yan log configuration
Word排版(小计)
Nodejs connect mysql
[Blue Bridge Cup 2017 preliminary] buns make up
Learning question 1:127.0.0.1 refused our visit
Linux yum安装MySQL
Punctual atom stm32f103zet6 download serial port pin