当前位置:网站首页>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 !
边栏推荐
- 2020 WANGDING cup_ Rosefinch formation_ Web_ nmap
- Niuke novice monthly race 40
- Vs2019 first MFC Application
- [AGC009D]Uninity
- Software testing and quality learning notes 3 -- white box testing
- Hutool中那些常用的工具类和方法
- FTP文件上传文件实现,定时扫描文件夹上传指定格式文件文件到服务器,C语言实现FTP文件上传详解及代码案例实现
- Wangeditor rich text component - copy available
- [CDH] modify the default port 7180 of cloudera manager in cdh/cdp environment
- Case analysis of data inconsistency caused by Pt OSC table change
猜你喜欢

【yarn】Yarn container 日志清理

分布式节点免密登录

QT creator runs the Valgrind tool on external applications

AI benchmark V5 ranking
![[yarn] CDP cluster yarn configuration capacity scheduler batch allocation](/img/85/0121478f8fc427d1200c5f060d5255.png)
[yarn] CDP cluster yarn configuration capacity scheduler batch allocation

Pytoch Foundation

2019腾讯暑期实习生正式笔试

Machine learning -- census data analysis

4. Install and deploy spark (spark on Yan mode)

Come and walk into the JVM
随机推荐
QT creator test
[Blue Bridge Cup 2017 preliminary] buns make up
Vs2019 desktop app quick start
Learn winpwn (3) -- sEH from scratch
vs2019 桌面程序快速入门
QT creator uses Valgrind code analysis tool
Word排版(小計)
MTCNN人脸检测
Request object and response object analysis
Valentine's Day flirting with girls to force a small way, one can learn
Case analysis of data inconsistency caused by Pt OSC table change
AcWing 242. A simple integer problem (tree array + difference)
Punctual atom stm32f103zet6 download serial port pin
2019腾讯暑期实习生正式笔试
wangeditor富文本引用、表格使用问题
[mrctf2020] dolls
yarn安装与使用
Number game
分布式節點免密登錄
How to build a new project for keil5mdk (with super detailed drawings)